在您的MainActivity的OnStart方法,運行此方法:
private void checkForPermissions() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_FINE_LOCATION);
} else {
initializeViews();
}
}
initializeViews()是使你的應用程序啓動正常人一樣。
然後實現onRequestPermissionsResult()如下:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_FINE_LOCATION) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initializeFragments();
} else {
openAlertDialog();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
MY_PERMISSIONS_REQUEST_FINE_LOCATION是一個最終詮釋場,這在我的情況是100的價值並不重要,只要您使用兩種方法中的相同變量。
如果用戶沒有讓許可,openAlertDialog()將被調用,這在我的應用程序如下:
private void openAlertDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("This app requires your location to function!");
alertDialogBuilder.setPositiveButton("Try again",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
checkForPermissions();
}
});
alertDialogBuilder.setNegativeButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:dk.redweb.intern.findetlokum"));
startActivity(i);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
這種方法使一個對話框窗口,用戶將得到再次獲取權限請求或打開應用程序的設置菜單之間的選擇。當用戶從設置返回到應用程序時,將再次調用onStart以檢查權限是否已被授予。
我認爲這不是處理用戶不想授予您權限的場景的正確方法。你應該考慮告訴你的用戶爲什麼你需要許可之後再問他。如果他不會授予,請在他試圖使用該功能之前回滾,並且只有在他再次嘗試使用時纔會再次詢問。 –
@GabrielVasconcelos我同意你的意見,只是在我的情況下,應用程序不斷監視位置。沒有位置權限,該應用將無法工作。我真的需要用戶授予權限。 –
然後問題不在於您是否需要許可,而在於您的用戶是否需要您的應用程序並知道它的用途。話雖如此,你可以關閉你的應用程序,並詢問用戶何時試圖回來,或者繼續詢問,但無論如何都要確保告訴用戶發生了什麼事情:爲什麼你再問一次或爲什麼應用程序關閉。 –