Request Permission after selected option(either camera or gallery) from intent chooser in android

拥有回忆 提交于 2019-12-05 10:38:06

问题


I have created an intent chooser containing Gallery, Photos and Camera apps. Now for the devices running on Android 6.0 or greater I want to ask the run time permissions after app is selected from chooser like if user selects gallery option I will ask storage permission only and in case if user select camera option I will ask camera and storage both permissions if not given before.

Can someone help me to do so?

Here is my code

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);
}

回答1:


Thanks to all for your support.

I solved it myself.

I appended below code in above method

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");
        }

Here is my broadcast receiver(IntentOptionReceiver) to notify which intent chooser option selected

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));
        }
    }
}

Do not forget to enter your broadcast receiver inside manifest.




回答2:


check permission using this code when ever.

what permission need give in to the array.

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);

    }

add this method also

@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;
        }
    }



回答3:


This method returns true if the app has Read External Storage Permission

 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;
        }

Wrap the actions that require permission with hasReadExternalStoragePermission method.

 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);
        }
    }

Please expand more on your own, use Manifest.permission_group instead of Manifest.permission, In places where you need to request multiple permission at once.

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



来源:https://stackoverflow.com/questions/44822840/request-permission-after-selected-optioneither-camera-or-gallery-from-intent-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!