从android中的意图选择器中选择选项(摄像机或图库)后请求权限

时间:2017-06-29 10:37:11

标签: android runtime-permissions android-intent-chooser

我创建了一个包含图库,照片和相机应用的意图选择器。现在,对于在Android 6.0或更高版本上运行的设备,我想在从选择器中选择应用程序之后询问运行时权限,例如,如果用户选择了库选项,我将只询问存储权限,如果用户选择了相机选项,我会询问相机和存储如果之前没有给出这两种权限。

有人可以帮我这样做吗?

这是我的代码

public void openImageIntent() {
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String fname = "ABCD_" + timeStamp;
    final File sdImageMainDirectory = new File(storageDir, fname);
    fileUri = Uri.fromFile(sdImageMainDirectory);

    // Camera.
    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    final PackageManager packageManager = getPackageManager();
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam) {
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        cameraIntents.add(intent);
    }

    //Gallery.
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    //Create the Chooser
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));


    startActivityForResult(chooserIntent, 65530);
}

3 个答案:

答案 0 :(得分:2)

感谢大家的支持。

我自己解决了。

我在上面的方法

中添加了以下代码
Intent receiver = new Intent(MainActivity.this, IntentOptionReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
        //Create the Chooser
        final Intent chooserIntent;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
            chooserIntent = Intent.createChooser(galleryIntent, "Select Source", pendingIntent.getIntentSender());
        } else {
            chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
        }

这是我的广播接收器(IntentOptionReceiver),用于通知选择了哪个意图选择器选项

public class IntentOptionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        for (String key : intent.getExtras().keySet()) {
            Log.e("intentOptionReceiver", "Intent option clicked info" + intent.getExtras().get(key));
        }
    }
}

不要忘记在清单中输入您的广播接收器。

答案 1 :(得分:0)

在任何时候使用此代码检查权限。

需要为数组提供什么权限。

if ((ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

    }

也添加此方法

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_CODE:
                if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

答案 2 :(得分:0)

  

如果应用具有“读取外部存储权限”

,则此方法返回true
 private boolean hasReadExternalStoragePermission() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                int permissionCheck = checkSelfPermission(getActivity(),
                        Manifest.permission.READ_EXTERNAL_STORAGE);
                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE);
                    return false;
                }
                return true;
            }
            return true;
        }
  

使用hasReadExternalStoragePermission方法包装需要权限的操作。

 public void openGallery() {

        if (hasReadExternalStoragePermission()) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, REQUEST_IMAGE_FROM_GALLERY);
        }
    }

请自行扩展,使用Manifest.permission_group而不是Manifest.permission,在需要一次请求多个权限的地方。

https://developer.android.com/training/permissions/requesting.html