App运行时弹出权限请求

App运行时弹出权限请求_第1张图片
2017-3-24

对于有的手机在第一次安装 app 时,会自动弹出权限请求;但有的却不会,例如 android 6.0 系统。

[1] 需求--做一个例如下图的权限请求

App运行时弹出权限请求_第2张图片
自定义的包涵多个权限请求

一般一个 app 有多种权限请求,基本的包括WRITE_EXTERNAL_STORAGE、WRITE_CONTACTS、READ_PHONE_STATE等。下面以请求CAMERA、WRITE_EXTERNAL_STORAGE、WRITE_CONTACTS为例。

App运行时弹出权限请求_第3张图片
单独的权限请求

[2] 实现过程

[2.1] 在 Manifest 文件中添加你需要申请的权限




[2.2] 在 Activity 中

final private int MY_PERMISSIONS_REQUEST_READ_CONTACTS=124;
    private static final String TAGLOG = "Contacts";
    private void insertDummyContact() {
        ArrayList operations = new ArrayList(2);
        ContentProviderOperation.Builder op =
                ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
        operations.add(op.build());
        op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                        "__DUMMY CONTACT from runtime permissions sample");
        operations.add(op.build());

      
        ContentResolver resolver = getContentResolver();
        try {
            resolver.applyBatch(ContactsContract.AUTHORITY, operations);
        } catch (RemoteException e) {
          
        } catch (OperationApplicationException e) {
   
        }
    }
 private void insertDummyContactWrapper() {
        List permissionsNeeded = new ArrayList();

        final List permissionsList = new ArrayList();
        if (!addPermission(permissionsList, Manifest.permission.CAMERA))
            permissionsNeeded.add("Camera");
        if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
            permissionsNeeded.add("Storage");
        if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
            permissionsNeeded.add("Write Contacts");

        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {
                String message = "You need to grant access to " + permissionsNeeded.get(0);
                for (int i = 1; i < permissionsNeeded.size(); i++)
                    message = message + ", " + permissionsNeeded.get(i);
                showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(StartActivity.this,permissionsList.toArray(new String[permissionsList.size()]),
                                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                            }
                        });
                return;
            }
            ActivityCompat.requestPermissions(StartActivity.this,permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            return;
        }

        insertDummyContact();
    }
private boolean addPermission(List permissionsList, String permission) {
        int hasWriteContactsPermission = ContextCompat.checkSelfPermission(StartActivity.this,
                Manifest.permission.CAMERA);
        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
       
            if (!ActivityCompat.shouldShowRequestPermissionRationale(StartActivity.this,permission))
                return false;
        }
        return true;
    }

private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(StartActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }
 @Overrid
 public void onRequestPermissionsResult(int requestCode,String permissions[],int[]grantResults){
        switch(requestCode){
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
            {

                Map perms = new HashMap();
         
                perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.WRITE_CONTACTS, PackageManager.PERMISSION_GRANTED);
            
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
             
                if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
                    insertDummyContact();
                } else {
                    Toast.makeText(StartActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
                            .show();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

[2.3]记得在 onCreate() 方法下调用哦

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
       insertDummyContactWrapper();
        L.d(TAG,"请求权限");
    }

[3] 分享

最近看了一本书--《柴静的气场法则》,没有看《看见》时的那种心跳的感觉,但却有平淡中的强大力量。喜欢书中的这样一句话

内心独立,倔强生长

你可能感兴趣的:(App运行时弹出权限请求)