在我的应用程序中,我想对存储
和相机
使用运行时权限
。
为此,我编写了下面的代码,它对我有用,但我想知道用户是否单击“允许”选项。
private static final int CAMERA_REQ = 2008;
private static final int STORAGE_REQ = 2005;
@OnClick(R.id.newAddFrag_uploadImageRootLay)
void uploadImage() {
new MaterialDialog.Builder(getActivity())
.title("Select")
.items(R.array.uploadImages)
.titleGravity(GravityEnum.CENTER)
.itemsGravity(GravityEnum.CENTER)
.typeface("IranSans.ttf", "IranSans.ttf")
.itemsIds(R.array.itemIds)
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
switch (which) {
case 0:
if (checkIfStorage(context)) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, REQUEST_PICK_PHOTO);
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_REQ);
}
break;
case 1:
if (checkIfCamera(context)) {
captureImage();
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, CAMERA_REQ);
}
break;
}
}
})
.show();
}
private boolean checkIfCamera(Context context) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkIfStorage(Context context) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
newAddFrag_uploadImageRootLay.setEnabled(true);
newAddFrag_uploadImageSuccessTxt.setEnabled(true);
newAddFrag_uploadImageLay.setEnabled(true);
}
}
if (requestCode == CAMERA_REQ) {
Log.e("permissionsLog", "CAMERA");
}
if (requestCode == STORAGE_REQ) {
Log.e("permissionsLog", "STORAGE");
}
}
最佳答案
请求权限时隐含以下规则:
- 如果您在
android.support.v4.app.Fragment
中请求权限,您只需调用requestPermissions
(因为它已在支持库中提供)。 - 如果您在 Fragment 中调用
ActivityCompat.requestPermissions
,则onRequestPermissionsResult
回调将传递给 Activity,而不是Fragment
。
由于您在 android.support.v4.app.Fragment
中请求权限,因此只需使用 requestPermissions
或在 Activity
中覆盖 onRequestPermissionsResult
并在那里处理结果。
关于java - 如何检查运行时权限中点击 "Allow"选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50836967/