【Android】使用PermissionsDispatcher動態(tài)權限庫進行權限適配

PermissionsDispatcher

PermissionsDispatcher是基于注解來寫的庫,即在需要的方法上添加對應的注解,然后它會在適當?shù)臅r候調用被注解過的對應的方法。

PermissionsDispatcher官方對其解釋:
PermissionsDispatcher provides a simple annotation-based API to handle runtime permissions.
// PermissionsDispatcher提供了一個簡單的基于注解的API來處理運行時權限。
This library lifts the burden that comes with writing a bunch of check statements whether a permission has been granted or not from you, in order to keep your code clean and safe.
這個庫可以通過編寫一堆檢查語句來解除這個負擔,這些檢查語句是為了讓代碼保持干凈和安全,是否授予您的權限。


1.在項目中引入PermissionsDispatcher

在app module的build.gradle文件中添加一下內容(${latest.version}更換為最新的版本號):

dependencies {
  compile("com.github.hotchemi:permissionsdispatcher:${latest.version}") {
      // if you don't use android.app.Fragment you can exclude support for them
      // 如果你不使用andorid.app.Fragment,可以排除對它們的支持。
      exclude module: "support-v13"
  }
  annotationProcessor "com.github.hotchemi:permissionsdispatcher-processor:${latest.version}"
}

在project的build.gradle中添加如下內容:

repositories {
  jcenter()
  maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}

2.在AndroidManifest.xml文件中配置應用所需要的權限

<uses-permission android:name="android.permission.CAMERA" />

3.添加注解(這里以在Activity中的使用為例)

PermissionsDispatcher introduces only a few annotations, keeping its general API concise:
// PermissionsDispatcher引入了一些注解,使其API簡潔

NOTE: Annotated methods must not be private.
// 注意:注解方法不能使私有的。

PermissionsDispatcher目前支持下面5個注解:

Annotation(注解) Required(是否必須使用) Description(描述/說明)
@RuntimePermissions ? Register an Activity or Fragment(we support both) to handle permissions.
@NeedsPermission ? Annotate a method which performs the action that requires one or more permissions.
@OnShowRationale Annotate a method which explains why the permission/s is/are needed. It passes in a PermissionRequest object which can be used to continue or abort the current permission request upon user input.
@OnPermissionDenied Annotate a method which is invoked if the user doesn't grant the permissions.
@OnNeverAskAgain Annotate a method which is invoked if the user chose to have the device "never ask again" about a permission.
  • 添加@RuntimePermissions注解:
    這是必須使用的注解,在想要進行權限申請的Activity或者Fragment上使用:
// 1.Register an Activity or Fragment(we support both) to handle permissions.
//   注冊一個Activity或Fragment(我們支持兩者)來處理權限。[必須的注解]
@RuntimePermissions
public class MainActivity extends AppCompatActivity {

}
  • 添加@NeedsPermission注解:
    必須使用的注解,標注在你要獲取權限的方法上,括號內傳入需要申請的一個或多個權限,在獲取到權限后會回調該方法。
@RuntimePermissions
public class MainActivity extends AppCompatActivity {

    // 2.Annotate a method which performs the action that requires one or more permissions.
    //   注解一個執(zhí)行需要獲取一個或多個權限的操作的方法。[必須的注解]
    @NeedsPermission(Manifest.permission.CAMERA)
    void showCamera() {
        Toast.makeText(this, "已獲取到相機權限", Toast.LENGTH_SHORT).show();
    }

}
  • 添加@OnShowRationale注解:
    非必要注解,注解在用戶首次拒絕后,再次獲取權限時解釋為什么需要獲取權限的方法上。
    // 3.Annotate a method which explains why the permission/s is/are needed. It passes in a
    // PermissionRequest object which can be used to continue or abort the current
    // permission request upon user input.
    // 注解一種解釋為什么需要權限的方法(注解用戶首次拒絕后,再次獲取權限時給出提示的方法)。它通過PermissionRequest對象,
    // 該對象可用于在用戶輸入時繼續(xù)或中止當前權限請求。[非必須的注釋]
    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(R.string.permission_camera_rationale)
                .setPositiveButton("允許", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒絕", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }
  • 添加@OnPermissionDenied注解:
    非必要注解,注解一個用戶拒絕授權時回調的方法。
    // 4.Annotate a method which is invoked if the user doesn't grant the permissions
    //  注解一個用戶拒絕授權時回調的方法。[非必須的注釋]
    @OnPermissionDenied(Manifest.permission.CAMERA)
    void showDeniedForCamera() {
        Toast.makeText(this, "相機權限許可被拒絕,請考慮給予權限以便進行拍照操作。", Toast.LENGTH_SHORT).show();
    }
  • 添加@OnNeverAskAgain注解:
    非必要注解,注解一個用戶選擇"不再詢問"時進行提示的回調方法。

注:也可在這里跳轉進入到權限設置頁。

    // 5.Annotate a method which is invoked if the user chose to have the device "never ask again"
    // about a permission
    // 注解一個用戶選擇"不再詢問"時進行提示的回調方法。[非必須的注釋]
    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void showNeverAskForCamera() {
        Toast.makeText(this, "相機許可被拒絕,不再進行詢問。", Toast.LENGTH_SHORT).show();
    }

4.將權限管理委托給生成的方法(使用&狀態(tài)回調)

  • 主動請求獲取權限
    在編譯過程中,PermissionsDispatcher會根據([Activity Name] + PermissionsDispatcher)的命名規(guī)則生成一個類,您可以使用它安全地訪問這些受保護的方法。

注:如MainActivity生成后的類名為MainActivityPermissionsDispatcher

那么,我們可以通過以下方法去獲取相機權限:

    // NOTE: delegate the permission handling to generated method.
    // 注意:將權限處理委托給生成的方法。
    MainActivityPermissionsDispatcher.showCameraWithPermissionCheck(MainActivity.this);
  • 在onRequestPermissionsResult中添加回調
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        // 注意:將權限處理委托給生成的方法。
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

MainActivty.java代碼

// 1.Register an Activity or Fragment(we support both) to handle permissions.
//   注冊一個Activity或Fragment(我們支持兩者)來處理權限。[必須的注解]
@RuntimePermissions
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.main_btn_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // NOTE: delegate the permission handling to generated method.
                // 注意:將權限處理委托給生成的方法。
                MainActivityPermissionsDispatcher.showCameraWithPermissionCheck(MainActivity.this);
            }
        });
    }

    // 2.Annotate a method which performs the action that requires one or more permissions.
    //   注解一個執(zhí)行需要獲取一個或多個權限的操作的方法。[必須的注解]
    @NeedsPermission(Manifest.permission.CAMERA)
    void showCamera() {
        Toast.makeText(this, "已獲取到相機權限", Toast.LENGTH_SHORT).show();
    }

    // 3.Annotate a method which explains why the permission/s is/are needed. It passes in a
    // PermissionRequest object which can be used to continue or abort the current
    // permission request upon user input.
    // 注解一種解釋為什么需要權限的方法(注解獲取權限時給出提示的方法)。它通過PermissionRequest對象,
    // 該對象可用于在用戶輸入時繼續(xù)或中止當前權限請求。[非必須的注釋]
    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(R.string.permission_camera_rationale)
                .setPositiveButton("允許", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒絕" new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 4.Annotate a method which is invoked if the user doesn't grant the permissions
    //  注解一個用戶拒絕授權時回調的方法。[非必須的注釋]
    @OnPermissionDenied(Manifest.permission.CAMERA)
    void showDeniedForCamera() {
        Toast.makeText(this, "相機權限許可被拒絕,請考慮給予權限以便進行拍照操作。", Toast.LENGTH_SHORT).show();
    }

    // 5.Annotate a method which is invoked if the user chose to have the device "never ask again"
    // about a permission
    // 注解一個用戶選擇"不再詢問"時進行提示的回調方法。[非必須的注釋]
    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void showNeverAskForCamera() {
        Toast.makeText(this, "相機許可被拒絕,不再進行詢問。", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        // 注意:將權限處理委托給生成的方法。
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,323評論 25 708
  • 本文出處:炎之鎧csdn博客:http://blog.csdn.net/totond炎之鎧郵箱:yanzhikai...
    炎之鎧閱讀 13,304評論 15 86
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,692評論 19 139
  • 文/蘇坡六 1 閑來無事重新溫習了《三國》我依舊非常喜歡曹操這個人。他是一位文學、軍事、政治才能兼?zhèn)涞囊晃蛔吭降拇?..
    蘇坡六閱讀 1,383評論 1 0
  • 不管從基因層面、分子層面、細胞層面,還是器官層面,地球上的動物、植物和真菌,全都有著證據確鑿的相似性。這一切都提示...
    宮曉杰閱讀 124評論 0 0

友情鏈接更多精彩內容