我正在开发基于cordova的Android项目,我有一个使用GPS位置的类,我想实现新的权限运行时。
我已经关注GitHub上的官方文档和google项目,但是我收到以下错误:
java.lang.NullPointerException:尝试调用虚拟方法&android; .content.getPackageManager()在空对象引用上
在这一行:
if(ActivityCompat.shouldShowRequestPermissionRationale(GpsTrackingActivity.this,Manifest.permission.ACCESS_FINE_LOCATION))
以下是代码:
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(GpsTrackingActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
android.widget.Toast.makeText(getApplicationContext(),"GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", android.widget.Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG_DBG, "Permission Granted, Now you can access location data.");
} else {
Log.i(TAG_DBG, "Please request permission");
}
break;
}
}
public void startTravel(String travelId, CarProperties car) {
Log.i(TAG_DBG, "L'utilisateur � appuy� sur Start");
//askForPermission(Manifest.permission.ACCESS_FINE_LOCATION,LOCATION);
if (checkPermission()) {
Log.i(TAG_DBG," Permission already granted");
} else {
Log.i(TAG_DBG, "Please request permission");
}
if (!checkPermission()) {
requestPermission();
} else {
Log.i(TAG_DBG," Permission already granted");
}
location = locationManager.getLastKnownLocation(provider);
//fb:bb#105: minTime to 1/2s instead of 1s to increase the number of fixes calculating effiMiles
locationManager.requestLocationUpdates(provider, 500, 10, this);
...
...
...
}
我做错了什么?