对于 API 级别 23(使用 checkSelfPermission),我有一个很好的 GetGeoLocation 应用程序。但是,然后我必须使其与 API 级别 21 兼容。因此,checkSelfPermission 不起作用,因为它是在 API 级别 23 中引入的。
所以,我改变了代码来适应这个:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckForCoarseLocationPermission();
}
private void CheckForCoarseLocationPermission()
{
if (android.os.Build.VERSION.SDK_INT >= 23)
{
// ANDROID 6.0 AND UP!
boolean accessCoarseLocationAllowed = false;
try
{
// Invoke checkSelfPermission method from Android 6 (API 23 and UP)
java.lang.reflect.Method methodCheckPermission = Activity.class.getMethod("checkSelfPermission", java.lang.String.class);
Object resultObj = methodCheckPermission.invoke(this, Manifest.permission.ACCESS_COARSE_LOCATION);
int result = Integer.parseInt(resultObj.toString());
if (result == PackageManager.PERMISSION_GRANTED)
{
accessCoarseLocationAllowed = true;
}
}
catch (Exception ex)
{
}
if (accessCoarseLocationAllowed)
{
Log.v("TAG","Granted");
LocationManager locationManager= (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,new LocationListener());//ERROR Happening Here!!!!!!!!!!!
}
try
{
// We have to invoke the method "void requestPermissions (Activity activity, String[] permissions, int requestCode) "
// from android 6
java.lang.reflect.Method methodRequestPermission = Activity.class.getMethod("requestPermissions", java.lang.String[].class, int.class);
methodRequestPermission.invoke(this, new String[]
{
Manifest.permission.ACCESS_FINE_LOCATION
}, 0x12345);
}
catch (Exception ex)
{
}
}
}
现在,LocationManager.requestLocationUpdate 给出错误
调用需要权限,这可能会被用户拒绝:代码应明确检查权限是否可用(使用checkPermission
)或明确处理潜在的SecurityException
更少
如果我想将 LocationManager 和 CheckPermission 用于 API 级别 >=21,如何解决它。
请帮忙。