我正在尝试实现运行时权限,但是在FragmentActivity
接收时几乎没有问题onRequestPermissionResult()
。该checkPermissions()
方法效果很好,但onRequestPermissionResult()
在用户允许或拒绝权限后永远不会调用。
当显示请求权限的系统对话框时,MyActivity.onDestroy()
永远不会调用。它与这个问题有关吗?
我的设备是 Nexus 5X (Android 6.0),Target SDK 版本是 23。最低支持 SDK 版本是 15。当然,我在 build.gradle 中写了所需的权限AndroidManifest.xml
并添加了 v23 支持库。
这是我的代码:
public class MyActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermissions();
}
private void checkPermissions(){
String[] dangerousPermissions = {
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.GET_ACCOUNTS,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
};
for(String permission : dangerousPermissions){
if (!hasPermission(permission)) {
Log.e("permission.debug", "need to grant " + permission);
ActivityCompat.requestPermissions(this, dangerousPermissions, 4);
}
}
}
public boolean hasPermission(String permission){
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d("permission.debug", " request code " + requestCode);
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == 0 && Manifest.permission.READ_PHONE_STATE.equals(permissions[i])) {
initiate();
}
}
}
}
这是我的代码的日志:
E/permission.debug: need to grant android.permission.READ_PHONE_STATE
E/permission.debug: need to grant android.permission.GET_ACCOUNTS
E/permission.debug: need to grant android.permission.WRITE_EXTERNAL_STORAGE
E/permission.debug: need to grant android.permission.RECORD_AUDIO
谢谢你。