試試這個方法:
public boolean isStoragePermissionGranted()
{
if (Build.VERSION.SDK_INT >= 23)
{
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)
{
Log.v(TAG,"Permission is granted");
return true;
}
else
{
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else
{
//permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted <23");
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED)
{
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
else
{
Log.v(TAG,"Permission denied");
}
}
這樣,如果權限被授予它會來這裏:
Log.v(TAG,"Permission is granted");
如果許可尚未批准,它會來這裏:
Log.v(TAG,"Permission is revoked");
並試圖獲得許可。
如果用戶授予在運行時的權限:
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
如果用戶否認:
Log.v(TAG,"Permission denied");
如果版本低於Marshamallow,即低於API 23
的話,那就來這裏:
Log.v(TAG,"Permission is granted <23");
來源
2017-01-23 07:18:39
OBX
入住這http://stackoverflow.com/a/31925748/2435238 – sJy
您應該遵循關於[運行時權限](https://developer.android.com/training/permissions/requesting.html)的指南。這通常是Android基礎知識的良好開端 – AxelH