是否必须在Activity中处理Android 6.0运行时权限检查回调?

时间:2015-10-19 15:42:04

标签: android callback android-6.0-marshmallow

基本上,我想为我的应用程序创建一个包装器,以使用我自己的回调来处理运行时权限检查。我想做一些相当于在requestPermissions方法中添加新回调或在此函数中覆盖Activity方法onRequestPermissionsResult,因此我不必担心应用程序状态。这可能吗?

我知道还有其他方法可以使用requestCodeFragment来管理此问题,但我只是对此感到好奇。

参见示例:

    interface IPermissionResponse {
        void permissionGranted();
        void providePermissionRationale();
        void permissionDenied();
    }

    private final static int REQUEST_INTERNET = 1;

    @SuppressLint("NewApi")
    public static void checkInternetPermission(Activity activity, boolean giveRationale, IPermissionResponse callback) {

        if(!platformVersionCheck()){
            // not android M, proceed with permission granted
            callback.permissionGranted();
            return;
        }

        Context nContext = activity.getApplicationContext();

        // android M things...
        if(nContext.checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED){
            // permission granted
            callback.permissionGranted();
        } else {
            // permission not granted

            // provide additional rationale to the user if the permission was not granted
            // and the user would benefit from additional information about the use of the permission
            if(giveRationale && activity.shouldShowRequestPermissionRationale(Manifest.permission.INTERNET)){
              callback.providePermissionRationale();
            }

            // request the permission
            activity.requestPermissions(new String[] {Manifest.permission.INTERNET}, REQUEST_INTERNET
            /*, new IRequestPermissionCallback(){
            // create new callback here
                // if accepted, callback.permissionGranted
                // if denied, callback.permissionDenied
            }*/);

            // OR SOMETHING LIKE

            // handle the result callback ?????
//            activity.onRequestPermissionsResult(........){
//                // create new callback here
//                // if accepted, callback.permissionGranted
//                // if denied, callback.permissionDenied
//            };
        }
    }

    private static boolean platformVersionCheck() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

2 个答案:

答案 0 :(得分:2)

RxPermission可能会有帮助。

RxPermissions.getInstance(activity)
    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    .subscribe(new Action1<Boolean>() {
        @Override
        public void call(Boolean grant) {
            if (grant) {
                save(); // granted
            } else {
                Snackbar.make(mContainer, getString(R.string.no_permission),
                        Snackbar.LENGTH_LONG).show();
            }
        }
    });

答案 1 :(得分:0)

不,没有任何回调。要进行自动管理,您可以在此处查看:Permission library