我在我的登录界面上检查所需的权限。对话框弹出请求我需要的4个权限。一切正常,但是当对话框出现时,背景变成黑色,我的应用程序关闭(不会崩溃,只是关闭)。当我完成选择权限后,再次打开应用程序,它将从停止的地方继续运行。如何使应用程序在显示权限对话框时继续运行?我使用一个类来检查权限,并在登录活动中调用它。
这个类:
public abstract class RuntimePermissionsActivity extends AppCompatActivity {
private SparseIntArray mErrorString;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mErrorString = new SparseIntArray();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for (int permission : grantResults){
permissionCheck = permissionCheck + permission;
}
if ((grantResults.length>0) && permissionCheck == PackageManager.PERMISSION_GRANTED){
onPermissionsGranted(requestCode);
}
else {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}
public void requestAppPermissions(final String[] requestedPermissions, final int requestCode){
int stringId = 0;
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean shouldShowRequestPermissionRationale = false;
for (String permission : requestedPermissions){
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
shouldShowRequestPermissionRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if(permissionCheck != PackageManager.PERMISSION_GRANTED){
if(shouldShowRequestPermissionRationale){
ActivityCompat.requestPermissions(RuntimePermissionsActivity.this, requestedPermissions, requestCode);
}
else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
Toast.makeText(RuntimePermissionsActivity.this, "Please relaunch the application in order for the changes to take effect!", Toast.LENGTH_LONG).show();
}
}
else {
onPermissionsGranted(requestCode);
}
}
public abstract void onPermissionsGranted(int requestCode);
}
登录活动调用:
LoginActivity.super.requestAppPermissions(new
String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS);