我创建了一个小的权限助手,由于某些未知的原因,当我拒绝许可时,我得到了两次。第一个是正常的,登陆请求许可的活动。第二个是在重定向到上一个活动后拒绝权限时显示的。
感谢您的帮助,
在onResume方法中调用helper,如下所示:
@Override
protected void onResume() {
super.onResume();
if(permissionHelper.checkPermission(this, Manifest.permission.READ_CONTACTS)){
initContact();
}
}
然后是onActivityPermissionResult,看起来像这样
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permissionHelper.onRequestPermissionsResult(requestCode, grantResults, new PermissionHelper.PermissionListener() {
@Override
public void onPermissionGranted() {
initContact();
}
@Override
public void onPermissionDenied() {
Intent intent = new Intent(ContactActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
我的PermissionHelper看起来像这样:
public class PermissionHelper {
/**
* Two possible callback: granted or not.
*/
public interface PermissionListener {
void onPermissionGranted();
void onPermissionDenied();
}
private static PermissionHelper mInstance;
private static Activity mActivity;
private static String mPermission;
private static final int REQUEST_CODE = 1337;
private PermissionHelper() {
setmActivity(mActivity);
setmPermission(mPermission);
}
public static PermissionHelper getInstance(){
if(mInstance == null){
mInstance = new PermissionHelper();
}
return mInstance;
}
public static void setmActivity(Activity mActivity) {
PermissionHelper.mActivity = mActivity;
}
public static void setmPermission(String mPermission) {
PermissionHelper.mPermission = mPermission;
}
public static boolean checkPermission(Activity activity, String permission){
mActivity = activity;
mPermission = permission;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int perm = mActivity.checkSelfPermission(mPermission);
if (perm != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mActivity.requestPermissions(new String[]{mPermission}, REQUEST_CODE);
return false;
}
}
}
return true;
}
/**
* Must be called from Activity's onRequestPermissionsResult()
*/
public static void onRequestPermissionsResult(int requestCode,
int[] grantResults,
PermissionListener permissionListener
) {
switch (requestCode) {
case REQUEST_CODE: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
permissionListener.onPermissionGranted();
}
else{
permissionListener.onPermissionDenied();
}
break;
}
}
}
}
答案 0 :(得分:0)
所以我终于有时间解决它了。我第一次打电话给checkPermission
内的onResume
,这很糟糕。 onResume也在onRequestPermissionsResult
之后调用。所以我将第一个电话转移到onCreate
。