了解Android 6权限方法 [英] Understanding the Android 6 permission method

查看:68
本文介绍了了解Android 6权限方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Gallery中获取图像并将其设置为imageview,但是在Android 6中存在一些权限问题.以下是请求许可的方法.我应该要求读取外部存储还是写入外部存储?

I am trying to take an image from Gallery and set it to an imageview but in Android 6 there are some permission problems. Below is the method to ask for the permission. Should I ask for read external storage or write external storage?

这是我到目前为止所做的:

Here is what I have done so far:

    private static final int READ_CONTACTS_PERMISSIONS_REQUEST = 1;


    public void getPermissionToReadExternalStorage() {

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        if (shouldShowRequestPermissionRationale(
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    READ_CONTACTS_PERMISSIONS_REQUEST);
        }}}
    @Override
            public void onRequestPermissionsResult(int requestCode,
                                                   @NonNull String permissions[],
                                                   @NonNull int[] grantResults){
                // Make sure it's our original READ_CONTACTS request
                if (requestCode == READ_CONTACTS_PERMISSIONS_REQUEST) {
                    if (grantResults.length == 1 &&
                            grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(getActivity(), "Read Contacts permission granted", Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(getActivity(), "Read Contacts permission denied", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                }
            }

现在,我的点击侦听器可以从图库中选择数据:

Now my on click listener to pick data from the Gallery:

     pro.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            if (android.os.Build.VERSION.SDK_INT >= 23) {
                getPermissionToReadExternalStorage();
                if (getPermissionToReadExternalStorage () this???? <==)
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
            } else {
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
        }}

    });
    return v;
}

现在,我想获取方法getPermissionToReadExternalStorage()的结果,以便可以启动Android 6的选择图库活动.如何获取void类的结果? 另一件事是我必须为我的应用程序要求的每个权限编写方法吗?

Now I want to get result of the method getPermissionToReadExternalStorage() so I can start the Activity for picking gallery for Android 6. How can I get the result of the void class? And another thing is do I have to write method for every permission my app asks for?

推荐答案

所以我已经完全重写了代码以请求权限. 现在,它支持请求多个权限并以正确的结果运行代码. 它还可与preMarshmallow设备一起使用,因此在这种情况下,您不必检查和复制代码.

So I have completely rewritten the code to request permissions. Now it supports requesting for multiple permissions and running code with proper result. Also it works with preMarshmallow devices, so you don't have to check and copy the code in that case.

首先,使用以下代码创建一个Activity类(您可以扩展所需的任何活动之王,例如AppCompatActivity):

First, create an Activity class with this code (You can extend any king of activity you need, e.g. AppCompatActivity):

public abstract class PermissionActivity extends AppCompatActivity {

    private final ArrayList<PermissionListener> permissionListeners = new ArrayList<>();

    @SuppressWarnings("unused")
    public void requestPermissions(int requestCode, String[] requestPermissions, PermissionListener permissionListener) {
        requestPermissions(requestCode, requestPermissions, null, permissionListener);
    }

    @SuppressWarnings("unused")
    public void requestPermissions(final int requestCode, String[] requestPermissions, String message, final PermissionListener permissionListener) {
        final int[] grantResults = new int[requestPermissions.length];

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> list_notGranted = new ArrayList<>();

            for (String requestPermission : requestPermissions)
                if (ContextCompat.checkSelfPermission(this, requestPermission) != PackageManager.PERMISSION_GRANTED)
                    list_notGranted.add(requestPermission);

            if (list_notGranted.size() > 0) {
                permissionListeners.add(permissionListener);

                requestPermissions = list_notGranted.toArray(new String[list_notGranted.size()]);

                if (message != null) {
                    boolean shouldShowRequestPermissionRationale = false;

                    for (String permission : requestPermissions)
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                            shouldShowRequestPermissionRationale = true;
                            break;
                        }

                    if (shouldShowRequestPermissionRationale) {
                        final String[] f_requestPermissions = requestPermissions;

                        AlertDialog.Builder builder = new AlertDialog.Builder(this);

                        builder.setMessage(message);

                        DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {

                            @TargetApi(Build.VERSION_CODES.M)
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case DialogInterface.BUTTON_POSITIVE:
                                        PermissionActivity.super.requestPermissions(f_requestPermissions, requestCode);
                                        break;
                                    default:
                                        for (int i = 0; i < grantResults.length; i++)
                                            grantResults[i] = PackageManager.PERMISSION_DENIED;

                                        if (permissionListener != null)
                                            permissionListener.onResult(requestCode, f_requestPermissions, grantResults);
                                        break;
                                }
                            }
                        };

                        builder.setPositiveButton("OK", onClickListener);
                        builder.setNegativeButton("Cancel", onClickListener);

                        builder.show();
                    } else {
                        super.requestPermissions(requestPermissions, requestCode);
                    }
                } else {
                    super.requestPermissions(requestPermissions, requestCode);
                }
            } else {
                for (int i = 0; i < grantResults.length; i++)
                    grantResults[i] = PackageManager.PERMISSION_GRANTED;

                if (permissionListener != null)
                    permissionListener.onResult(requestCode, requestPermissions, grantResults);
            }
        } else {
            if (permissionListener != null) {
                for (int i = 0; i < grantResults.length; i++)
                    grantResults[i] = PackageManager.PERMISSION_GRANTED;

                permissionListener.onResult(requestCode, requestPermissions, grantResults);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        for (Iterator<PermissionListener> it = permissionListeners.iterator(); it.hasNext(); ) {
            PermissionListener permissionListener = it.next();
            if (permissionListener.onResult(requestCode, permissions, grantResults)) {
                it.remove();
            }
        }
    }

    public interface PermissionListener {

        boolean onResult(int requestCode, String[] requestPermissions, int[] grantResults);

    }
}

如果要从Fragments请求权限,请添加此类:

If you want to request permissions from Fragments, add this class:

public class PermissionFragment extends Fragment {

    @SuppressWarnings("unused")
    public void requestPermissions(int requestCode, String[] requestPermissions, PermissionActivity.PermissionListener permissionListener) {
        requestPermissions(requestCode, requestPermissions, null, permissionListener);
    }

    @SuppressWarnings("unused")
    public void requestPermissions(final int requestCode, String[] requestPermissions, String message, PermissionActivity.PermissionListener permissionListener) {
        ((PermissionActivity) getActivity()).requestPermissions(requestCode, requestPermissions, message, permissionListener);
    }
}

您的活动和片段应该扩展这些类,而不是标准的类.

Your Activities and Fragments should extend these classes instead of the standart ones.

现在您可以通过调用方法来请求权限了:

Now you are ready to request the permissions by calling a method:

requestPermissions(int requestCode, String[] requestPermissions, PermissionListener permissionListener)

如果该应用需要许可才能工作,则应调用此方法并指定消息,说明为什么需要该许可.

If the permission is required for the app to work, you should call this method and specify the message saying why the permission is required.

requestPermissions(int requestCode, String[] requestPermissions, String message, PermissionListener permissionListener)

不要误导默认方法,

// DON'T USE THIS ONE!
requestPermissions(String[] requestPermissions, int requestCode)
// DON'T USE THIS ONE!

以下是请求联系的示例:

Here is the example of requesting contacts:

private void requestAndLoadContacts() {
    String[] permissions = new String[]{Manifest.permission.READ_CONTACTS};

    requestPermissions(REQUEST_PERMISSIONS_CONTACTS, permissions, "Read contacts permission is required for the app to work!", new PermissionListener() {

        @Override
        public boolean onResult(int requestCode, String[] requestPermissions, int[] grantResults) {
            // Check if the requestCode is ours
            if (requestCode == REQUEST_PERMISSIONS_CONTACTS) {
                // Check if the permission is correct and is granted
                if (requestPermissions[0].equals(Manifest.permission.READ_CONTACTS) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission granted
                    // Calling a method to actually load the contacts
                    loadContacts();
                } else {
                    // Permission not granted
                    Toast.makeText(MainActivity.this, "Access denied!", Toast.LENGTH_SHORT).show();
                }

                return true;
            }

            return false;
        }
    });
}

注意: 当您实现PermissionListener时,请不要忘记在 requestCode是正确的密码返回true ,否则PermissionListener 不会被删除从ArrayList中,您很可能会发生少量内存泄漏.

NOTE: When you implement the PermissionListener, don't forget to return true when the requestCode is the correct one, otherwise the PermissionListener won't be removed from the ArrayList and you'll most likely get a small memory leak.

这篇关于了解Android 6权限方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆