How to ask permission to access gallery on android M.?

后端 未结 2 1755
无人共我
无人共我 2020-11-30 12:12

I have this app that will pick image to gallery and display it to the test using Imageview. My problem is it won\'t work on Android M. I can pick image but won\'t show on my

相关标签:
2条回答
  • 2020-11-30 13:06

    Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

    Type 1- When your app requests permissions, the system presents a dialog box to the user. When the user responds, the system invokes your app's onRequestPermissionsResult() method, passing it the user response. Your app has to override that method to find out whether the permission was granted. The callback is passed the same request code you passed to requestPermissions().

    private static final int PICK_FROM_GALLERY = 1;
    
    ChoosePhoto.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick (View v){
        try {
            if (ActivityCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(EditProfileActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
            } else {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
      }
    });
    
    
    @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults)
        {
           switch (requestCode) {
                case PICK_FROM_GALLERY:
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                      Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                      startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
                    } else {
                        //do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
                    }
                    break;
            }
        }
    

    Type 2- If you want to give runtime permission back to back in one place then you can follow below link

    Android 6.0 multiple permissions

    And in Manifest add permission for your requirements

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    

    Note- If Manifest.permission.READ_EXTERNAL_STORAGE produce error then please replace this with android.Manifest.permission.READ_EXTERNAL_STORAGE.

    ==> If you want to know more about runtime permission then please follow below link

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

    -----------------------------UPDATE 1--------------------------------

    Runtime Permission Using EasyPermissions

    EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher.

    Installation Add dependency in App level gradle

     dependencies {
    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'
    
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    }
    

    Your Activity (or Fragment) override the onRequestPermissionsResult method:

     @Override
         public void onRequestPermissionsResult(int requestCode, String[] 
        permissions, int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions,grantResults);
    
            // Forward results to EasyPermissions
            EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        }
    

    Request Permissions

    private static final int LOCATION_REQUEST = 222;
    

    Call this method

    @AfterPermissionGranted(LOCATION_REQUEST)
    private void checkLocationRequest() {
       String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            // ...
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this,"Please grant permission",
                    LOCATION_REQUEST, perms);
        }
    }
    

    Optionally, for a finer control, you can have your Activity / Fragment implement the PermissionCallbacks interface.

    implements EasyPermissions.PermissionCallbacks

     @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Some permissions have been granted
        // ...
    }
    
    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        // ...
    }
    

    Link -> https://github.com/googlesamples/easypermissions

    -----------------------------UPDATE 2 For KOTLIN--------------------------------

    Runtime Permission Using florent37

    Installation Add dependency in App level gradle

    dependency

    implementation 'com.github.florent37:runtime-permission-kotlin:1.1.2'
    

    In Code

            askPermission(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) {
           // camera or gallery or TODO
        }.onDeclined { e ->
            if (e.hasDenied()) {
                AlertDialog.Builder(this)
                    .setMessage(getString(R.string.grant_permission))
                    .setPositiveButton(getString(R.string.yes)) { dialog, which ->
                        e.askAgain()
                    } //ask again
                    .setNegativeButton(getString(R.string.no)) { dialog, which ->
                        dialog.dismiss()
                    }
                    .show()
            }
    
            if (e.hasForeverDenied()) {
                e.goToSettings()
            }
        }
    

    Link-> https://github.com/florent37/RuntimePermission

    0 讨论(0)
  • 2020-11-30 13:09
    public void pickFile() {
            int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
                    CAMERA);
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                        getActivity(),
                        new String[]{CAMERA},
                        PERMISSION_CODE
                );
                return;
            }
            openCamera();
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                               @NonNull int[] grantResults) {
            if (requestCode == PERMISSION_CODE) {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                }
            }
        }
    
        private void openCamera() {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAMERA_CODE);
        }
    
    
    <uses-permission android:name="android.permission.CAMERA" />
    
    0 讨论(0)
提交回复
热议问题