我使用以下代码来获取读写权限,但问题是,通过在oncreate中使用这段代码,我的应用程序启动两次而不是一次。我该如何解决这个问题?
// **check if app has permission 1**//
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE }, 2909);
} else {
// continue with your code
}
} else {
// continue with your code
}
这里是oncreate之外的其余代码 -
// **check if app has permission 2**//
@Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("Permission", "Granted");
} else {
Log.e("Permission", "Denied");
}
return;
}
}
}
答案 0 :(得分:0)
您是否尝试过使用它来检查权限
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
如果授予或撤销许可,则返回此井......
答案 1 :(得分:-1)
对于此特定示例,您首先可以检查是否授予了权限
checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)
如果结果为false则请求权限
修改
更改if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
到
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && (checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) || checkSelfPermission( Manifest.permission.READ_EXTERNAL_STORAGE )
!= PackageManager.PERMISSION_GRANTED)))