android M 權限管理

public class PermissionHelper {

    public interface OnPermissionCallback
    {
        /**
         *
         * @param success
         * @return  true handled false not handle
         */
        public boolean onPermissionResult(boolean success);
    }

    private Context mContext;
    private final String PACKAGE = "package:";
    private final int REQUEST_CODE = 12;

    private OnPermissionCallback mOnPermissionCallback;

    public PermissionHelper(Context context, OnPermissionCallback onPermissionCallback) {
        if(context == null || onPermissionCallback == null)
        {
            throw new IllegalArgumentException();
        }
        else
        {
            mContext = context;
            mOnPermissionCallback = onPermissionCallback;
        }
    }

    /**
     * 判斷權限集合
     *
     * @param permissions 檢測權限的集合
     * @return List 沒有獲取權限的列表
     */
    public List<String> checkPermissions(String... permissions) {
        List<String> permissionsList = new ArrayList<String>();
        for (String permission : permissions) {
            if (!checkPermission(permission)) {
                permissionsList.add(permission);
            }
        }

        if (permissionsList != null && permissionsList.size() > 0){
            requestPermissions(permissionsList, REQUEST_CODE);
        }else{
            if(mOnPermissionCallback != null)
            {
                mOnPermissionCallback.onPermissionResult(true);
            }
        }

        return permissionsList;
    }

    /**
     * 判斷權限是否獲取
     *
     * @param permission 權限名稱
     * @return 已受權返回true,未受權返回false
     */
    public boolean checkPermission(String permission) {
        return ContextCompat.checkSelfPermission(mContext, permission) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 獲取權限
     *
     * @param resultCode
     * @return
     */
    public void requestPermissions(List<String> permissionsList, int resultCode) {
        if(permissionsList == null || permissionsList.isEmpty()) return;

        List<String> permissionsNeeded = new ArrayList<String>();
        for (String permission : permissionsList) {
            // 注意這裏要使用shouldShowRequestPermissionRationale而不要使用requestPermission方法
            // 由於requestPermissions方法會顯示不在詢問按鈕
            if (!ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext, permission)) {
                permissionsNeeded.add(permission);
            }
        }

        if (permissionsNeeded.size() > 0) {
            //若是用戶之前拒絕過改權限申請,則給用戶提示
            showMissingPermissionDialog();
        } else {
            //進行權限請求
            ActivityCompat.requestPermissions((Activity) mContext,
                    permissionsList.toArray(new String[permissionsList.size()]),
                    resultCode);
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch(requestCode){
            case REQUEST_CODE:
                boolean success = false;
                if(permissions != null && permissions.length > 0 && grantResults != null && grantResults.length > 0)
                {
                    for (int i = 0; i < grantResults.length; i++) {
                        success = grantResults[i] == PackageManager.PERMISSION_GRANTED;
                        if(!success) break;
                    }
                }

                boolean handle = false;
                if(mOnPermissionCallback != null)
                {
                    handle = mOnPermissionCallback.onPermissionResult(success);
                }

                if (!success && !handle) {
                    startAppSettings();
                }
                break;
        }
    }

    // 顯示缺失權限提示
    private void showMissingPermissionDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        final AlertDialog alertDialog = builder.create();

        builder.setMessage("當前應用缺乏必要權限。\n\n請點擊設置按鈕,進入應用信息界面打開所需權限。");
        // 拒絕, 退出應用
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                if(mOnPermissionCallback != null)
                {
                    mOnPermissionCallback.onPermissionResult(false);
                }
            }
        });

        builder.setPositiveButton("設置", new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                startAppSettings();
            }
        });

        builder.show();
    }

    // 啓動應用的設置
    public void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse( PACKAGE + mContext.getPackageName()));
        mContext.startActivity(intent);
    }
}

//引用代碼
 private PermissionHelper mPermissionHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPermissionHelper = new PermissionHelper(this, new PermissionHelper.OnPermissionCallback() {
            @Override
            public boolean onPermissionResult(boolean success) {
                if(success)
                {
                    doSuccess();
                }
                else
                {
                    finish();
                }
                 return true;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //判斷權限受權狀態
        mPermissionHelper.checkPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

以上代碼再這兩篇文章基礎上修改: Android 6.0RunTime Permission完美解決方案ide

Android M 新的運行時權限開發者須要知道的一切ui

相關文章
相關標籤/搜索