我請求用戶訪問或拒絕GPS的權限,如果用戶點擊訪問權限,然後我的代碼工作,但是當用戶點擊拒絕權限我不能夠打開另一個活動如果被拒絕的權限打開Android的新活動
這裏是我的代碼:
txtLocation = (TextView)findViewById(R.id.txtLocation);
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location;
if (network_enabled) {
boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED;
Log.d("permission", "onCreate: "+permissionGranted);
if(permissionGranted) {
// {Some Code}
} else {
// ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200);
}
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},
200);
}
location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
lat = location.getLongitude();
lon = location.getLatitude();
Log.d("lat", "onCreate: "+lat+","+lon);
txtLocation.setText(+lat+","+lon);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Latitude:"+lat+"\n"+"Longitude:"+lon);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d("", "onRequestPermissionsResult: "+requestCode);
Toast.makeText(MainActivity.this, "code", Toast.LENGTH_SHORT).show();
switch (requestCode) {
case 200: {
// If request is cancelled, the result arrays are empty.
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this, "Granted", Toast.LENGTH_SHORT).show();
}else if(grantResults[0] == PackageManager.PERMISSION_DENIED) {
Intent intent = new Intent(this,Homepage.class);
startActivity(intent);
}
}
default:{
Toast.makeText(MainActivity.this, "Denied", Toast.LENGTH_SHORT).show();
}
// other 'case' lines to check for other
// permissions this app might request
}
}
無法打開是什麼意思?它會崩潰嗎? –
@KamranAhmed不,它不會崩潰,但如果訪問被拒絕,我的代碼不會被調用,我無法訪問我的代碼中的被拒絕部分 – bipin
您可以使用調試來查看錯誤。 –