我正在尝试实现位置权限的运行时授权。具体实现如下:
public class MyLocationManager implements android.location.LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {
private static LocationManager m_locationManager;
private static final int REQUEST_COARSE_LOCATION = 999;
private static final int REQUEST_FINE_LOCATION = 998;
private String provider;
private Context mContext;
public void startListenLocation(Context context) {
this.mContext = context;
m_locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
...
if (Build.VERSION.SDK_INT >= 23 && ((ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION)) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_COARSE_LOCATION) ;
} else {
Location location = m_locationManager.getLastKnownLocation(provider);
}
...
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_COARSE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//compiler error on the following line
Location myLocation = m_locationManager.getLastKnownLocation(provider);
} else {
//Permission denied
}
return;
}
}
}
}
当我在onRequestPermissionResult()
中调用getLastKnownLocation()
时,出现了语法错误。它告诉我再次检查权限,即使我已经这样做了。那么有人可以告诉我这里的实现有什么问题吗?