喜這裏是爲Android M設置權限的幾個步驟,並記住你應該在清單文件中聲明相同的權限。
步驟1. 聲明全局變量:
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 0;
第2步 使用此代碼在您的主要活動
private void locationpermission() {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(activity
,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
步驟3 調用此方法在你onCreate方法,
locationpermission();
而且任何人p你可以從這裏打電話給你,每一個結果你都可以在覆蓋方法onRequestPermissionsResult這一個。
三江源
希望這將幫助你(Y)。