【发布时间】:2020-06-14 00:16:49
【问题描述】:
我在我的应用程序中遇到问题,我的应用程序需要读写权限,但是每当我的应用程序第一次打开时,我的应用程序崩溃并关闭,然后它会在后台请求权限,然后我需要重新启动它,然后它才能正常工作。我只在第一次运行时遇到问题。
这是我的代码
主要活动
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
checkPermissions();
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkPermissions(){
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1052);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
/* if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= android.content.pm.PackageManager.PERMISSION_GRANTED||
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= android.content.pm.PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.READ_EXTERNAL_STORAGE,
},
1052);*/
}
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1052: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED
&& grantResults[1] == android.content.pm.PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Enjoy This app", Toast.LENGTH_SHORT).show();
}
else {
android.widget.Toast.makeText(this, "Permission Denied, without your permission we cant share or download images to your device", android.widget.Toast.LENGTH_LONG).show();
// Permission denied - Show a message to inform the user that this app only works
// with these permissions granted
}
}
}
}
【问题讨论】:
标签: java android-studio android-permissions