我正在开发一个关于如何请求ACCESS_FINE_LOCATION权限的Android 6.0应用示例,就像在下图中一样。
选择DENY选项时,我想向用户显示一个自定义对话框,但它会抛出以下异常:
IllegalStateException - Can not perform this action after onSaveInstanceState
:
grantPermissionDialog.show(getSupportFragmentManager(),"GrantPermissionDialog");
在onRequestPermissionsResult方法
中@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_ACCESS_FINE_LOCATION){
if(grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Location permission granted", Toast.LENGTH_LONG).show();
}else{
grantPermissionDialog.show(getSupportFragmentManager(),"GrantPermissionDialog");
}
}
}
我想这是因为调用了getSupportFragmentManager()
方法。
这是我的GrantPermissionDialog代码。
public class GrantPermissionDialog extends DialogFragment {
private int statusCode;
private String message="El permiso de ubicación es necesario para que esta aplicación funcione.";
private String positiveButtonText="Salir";
private String negativeButtonText="Solicitar permiso";
public static int EXIT_APPLICATION=0;
public static int REQUEST_PERMISSION=1;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(message);
builder.setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
statusCode = EXIT_APPLICATION;
}
});
builder.setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
statusCode = REQUEST_PERMISSION;
}
});
return builder.create();
}
public int getStatusCode() {
return statusCode;
}
}
有关如何解决此问题的任何想法?
答案 0 :(得分:5)
这是一个众所周知的场景,并且得到了很好的解释here。根据那篇文章,它引起了
因为您尝试在保存活动状态后提交FragmentTransaction
您应该将show()对话框代码移动到“onPostResume()”并使用所述的标记here
private boolean mRequestPermissionsWithResult = false;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_ACCESS_FINE_LOCATION){
if(grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Location permission granted", Toast.LENGTH_LONG).show();
}else{
mRequestPermissionsWithResult = true;
}
}
}
@Override
protected void onPostResume() {
super.onPostResume();
if (mRequestPermissionsWithResult) {
grantPermissionDialog.show(getSupportFragmentManager(),"GrantPermissionDialog");
}
mRequestPermissionsWithResult = false;
}