onRequestPermissions结果未在对话片段中被调用
2022-08-31 15:59:50
我已经开始研究Android M运行时权限。在这里,我面临的问题是,如果从类调用,则不会在同一类中被调用。但是,如果从类或类调用,则在同一类中调用方法。requestPermissions
Dialog Fragment
onRequestPermissionsResult
Dialog fragment
requestPermissions
Activity
Fragment
onRequestPermissionsResult
这是我的示例代码:
public class ContactPickerDialog extends DialogFragment {
private static final int READ_CONTACTS_REQUEST_CODE = 12;
private Context mContext;
private void loadContact() {
if(hasPermission(mContext, Manifest.permission.READ_CONTACTS)){
new ContactSyncTask().execute();
} else {
this.requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, READ_CONTACTS_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
Logger.d("TAG", "dialog onRequestPermissionsResult");
switch (requestCode) {
case READ_CONTACTS_REQUEST_CODE:
// Check Permissions Granted or not
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
new ContactSyncTask().execute();
} else {
// Permission Denied
Toast.makeText(getActivity(), "Read contact permission is denied", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private static boolean hasPermission(Context context, String permission){
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
}
在代码中,我调用了类的方法。所以我期望在同一类中得到结果。requestPermissions
Dialog Fragment
任何帮助是值得赞赏的。提前致谢!
编辑:在这里,我添加更多细节,以便对其他人更有帮助。以前我使用getChildFragmentManager()来显示DialogFragment。
ContactPickerDialog dialog = new ContactPickerDialog();
dialog.show(getChildFragmentManager(), "Contact Picker");
但正如@CommonWare要求我使用活动来展示DialogFragment。我做了以下更改,并且有效。
ContactPickerDialog dialog = new ContactPickerDialog();
dialog.show(getActivity().getSupportFragmentManager(), "Contact Picker");