简体   繁体   English

如何在 android M. 上请求访问图库的权限?

[英]How to ask permission to access gallery on android M.?

I have this app that will pick image to gallery and display it to the test using Imageview.我有这个应用程序,它将选择图像到图库并使用 Imageview 将其显示给测试。 My problem is it won't work on Android M. I can pick image but won't show on my test.They say i need to ask permission to access images on android M but don't know how.我的问题是它不能在 Android M 上运行。我可以选择图像,但不会在我的测试中显示。他们说我需要请求许可才能在 android M 上访问图像,但不知道如何。 please help.请帮忙。

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.从 Android 6.0(API 级别 23)开始,用户在应用运行时授予应用权限,而不是在安装应用时授予权限。

Type 1- When your app requests permissions, the system presents a dialog box to the user.类型 1-当您的应用请求权限时,系统会向用户显示一个对话框。 When the user responds, the system invokes your app's onRequestPermissionsResult() method, passing it the user response.当用户响应时,系统调用您的应用程序的 onRequestPermissionsResult() 方法,将用户响应传递给它。 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().回调传递的请求代码与您传递给 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类型 2-如果您想在一个地方背靠背授予运行时权限,那么您可以点击以下链接

Android 6.0 multiple permissions Android 6.0 多重权限

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.注意 -如果 Manifest.permission.READ_EXTERNAL_STORAGE 产生错误,那么请将其替换为 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 https://developer.android.com/training/permissions/requesting.html

-----------------------------UPDATE 1-------------------------------- -----------------------------更新1------------------- -------------

Runtime Permission Using EasyPermissions使用 EasyPermissions 的运行时权限

EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher. EasyPermissions 是一个包装库,用于在面向 Android M 或更高版本时简化基本系统权限逻辑。

Installation Add dependency in App level gradle安装在 App 级 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:您的活动(或片段)覆盖 onRequestPermissionsResult 方法:

 @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.或者,为了更好的控制,您可以让您的 Activity / Fragment 实现 PermissionCallbacks 接口。

implements EasyPermissions.PermissionCallbacks实现 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链接 -> https://github.com/googlesamples/easypermissions

-----------------------------UPDATE 2 For KOTLIN-------------------------------- -----------------------------更新 2 对于 KOTLIN----------------- ---------------

Runtime Permission Using florent37使用 florent37 的运行时权限

Installation Add dependency in App level gradle安装在 App 级 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链接-> https://github.com/florent37/RuntimePermission

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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM