当我点击活动布局中的按钮时,我试图显示GPS坐标。以下是单击按钮时调用的方法:
@XmlElement
private Fighter fighter = DEFAULT_FIGHTER_OR_NULL_OR_WHATEVER;
我收到错误消息
通话需要获得用户拒绝的许可。代码应明确检查是否有权限。
我已经在public void getLocation(View view) {
TextView tv = (TextView) findViewById(R.id.gps_coord_view);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
tv.setText("Latitude: " + loc.getLatitude() + "\nLongitude: " + loc.getLongitude());
}
中授予了这些权限。在调用AndroidManifest
之前添加以下内容时,错误会得到处理并且应用程序会编译:
lm.getLastKnownLocation
然而,当我按下点击时调用getLocation的按钮时,应用程序崩溃了。到底是怎么回事?是否有更好/更简单的方法来获取设备的GPS坐标?
答案 0 :(得分:136)
使用Android API级别(23),我们需要检查权限。 https://developer.android.com/training/permissions/requesting.html
我遇到了同样的问题,但以下情况对我有用,我能够成功检索位置数据:
(1)确保您在Manifest中列出了您的权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
(2)确保您请求用户的权限:
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION );
}
(3)确保使用ContextCompat,因为它与旧的API级别兼容。
(4)在您的位置服务或初始化您的LocationManager并获取最后已知位置的类中,我们需要检查权限:
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
(5)在我的initLocationService方法的顶部包含@TargetApi(23)之后,这种方法只适用于我。
(6)我还将其添加到我的gradle构建中:
compile 'com.android.support:support-v4:23.0.1'
这是我的LocationService以供参考:
public class LocationService implements LocationListener {
//The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
//The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // 1 minute
private final static boolean forceNetwork = false;
private static LocationService instance = null;
private LocationManager locationManager;
public Location location;
public double longitude;
public double latitude;
/**
* Singleton implementation
* @return
*/
public static LocationService getLocationManager(Context context) {
if (instance == null) {
instance = new LocationService(context);
}
return instance;
}
/**
* Local constructor
*/
private LocationService( Context context ) {
initLocationService(context);
LogService.log("LocationService created");
}
/**
* Sets up location service after permissions is granted
*/
@TargetApi(23)
private void initLocationService(Context context) {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
try {
this.longitude = 0.0;
this.latitude = 0.0;
this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Get GPS and network status
this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (forceNetwork) isGPSEnabled = false;
if (!isNetworkEnabled && !isGPSEnabled) {
// cannot get location
this.locationServiceAvailable = false;
}
//else
{
this.locationServiceAvailable = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateCoordinates();
}
}//end if
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateCoordinates();
}
}
}
} catch (Exception ex) {
LogService.log( "Error creating location service: " + ex.getMessage() );
}
}
@Override
public void onLocationChanged(Location location) {
// do stuff here with location object
}
}
我目前只测试了Android Lollipop设备。 希望这对你有用。
答案 1 :(得分:42)
我想支持pre api 23的应用,而不是使用checkSelfPermission
我使用了try / catch
try {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (SecurityException e) {
dialogGPS(this.getContext()); // lets the user know there is a problem with the gps
}
答案 2 :(得分:37)
您引用的错误消息的最后一部分指出:
<div class="row ms-category">
<div class="col-category col-xs-3">
<a class="form-group level1" href="">title</a>
<a class="form-group level2" href="">title</a>
<a class="form-group level2" href="">title</a>
</div>
<div class="col-category col-xs-3">
<a class="form-group level1" href="">title</a>
<a class="form-group level2" href="">title</a>
<a class="form-group level2" href="">title</a>
</div>
<div class="col-category col-xs-3">
<a class="form-group level1" href="">title</a>
<a class="form-group level2" href="">title</a>
<a class="form-group level2" href="">title</a>
</div>
</div>
检查您是否拥有权限的更快/更简单的方法是使用...with ("checkPermission") or explicitly handle a potential "SecurityException"
包围您的代码。如果您有权限,请尝试&#39;部分将执行,如果你没有,“赶上”&#39;部分会。
答案 3 :(得分:4)
如果您正在处理动态权限和任何权限,例如ACCESS_FINE_LOCATION,则ACCESS_COARSE_LOCATION会出错&#34;无法解决方法PERMISSION_NAME&#34; 在这种情况下,请使用权限名称编写代码,然后重建您的这将重新生成清单(Manifest.permission)文件。
答案 4 :(得分:2)
使用我的客户类检查或请求许可
public class Permissons {
//Request Permisson
public static void Request_STORAGE(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},code);
}
public static void Request_CAMERA(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.CAMERA},code);
}
public static void Request_FINE_LOCATION(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},code);
}
public static void Request_READ_SMS(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.READ_SMS},code);
}
public static void Request_READ_CONTACTS(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.READ_CONTACTS},code);
}
public static void Request_READ_CALENDAR(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.READ_CALENDAR},code);
}
public static void Request_RECORD_AUDIO(Activity act,int code)
{
ActivityCompat.requestPermissions(act, new
String[]{Manifest.permission.RECORD_AUDIO},code);
}
//Check Permisson
public static boolean Check_STORAGE(Activity act)
{
int result = ContextCompat.checkSelfPermission(act,android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_CAMERA(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.CAMERA);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_FINE_LOCATION(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_READ_SMS(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_SMS);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_READ_CONTACTS(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_CONTACTS);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_READ_CALENDAR(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.READ_CALENDAR);
return result == PackageManager.PERMISSION_GRANTED;
}
public static boolean Check_RECORD_AUDIO(Activity act)
{
int result = ContextCompat.checkSelfPermission(act, Manifest.permission.RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED;
}
}
实施例
if(!Permissons.Check_STORAGE(MainActivity.this))
{
//if not permisson granted so request permisson with request code
Permissons.Request_STORAGE(MainActivity.this,22);
}
答案 5 :(得分:0)
如果您只是想检查权限(而不是请求权限),我写了一个简单的扩展名,如下所示:
fun BaseActivity.checkPermission(permissionName: String): Boolean {
return if (Build.VERSION.SDK_INT >= 23) {
val granted =
ContextCompat.checkSelfPermission(this, permissionName)
granted == PackageManager.PERMISSION_GRANTED
} else {
val granted =
PermissionChecker.checkSelfPermission(this, permissionName)
granted == PermissionChecker.PERMISSION_GRANTED
}
}
现在,如果我想检查权限,我可以像这样简单地传递一个权限:
checkPermission(Manifest.permission.READ_CONTACTS)