Android之6.0 权限申请封装
之前一篇博客初試了Android6.0系統(tǒng)的動(dòng)態(tài)權(quán)限申請(qǐng),成功之后開始思考將權(quán)限申請(qǐng)功能封裝以供更加方便的調(diào)用。
查閱6.0系統(tǒng)權(quán)限相關(guān)的API,整個(gè)權(quán)限申請(qǐng)需要調(diào)用三個(gè)方法:
1. ContextCompat.checkSelfPermission()?
檢查應(yīng)用是否擁有該權(quán)限,被授權(quán)返回值為PERMISSION_GRANTED,否則返回PERMISSION_DENIED
/*** Determine whether <em>you</em> have been granted a particular permission.** @param permission The name of the permission being checked.** @return {@link android.content.pm.PackageManager#PERMISSION_GRANTED} if you have the* permission, or {@link android.content.pm.PackageManager#PERMISSION_DENIED} if not.** @see android.content.pm.PackageManager#checkPermission(String, String)*/public static int checkSelfPermission(@NonNull Context context, @NonNull String permission) {if (permission == null) {throw new IllegalArgumentException("permission is null");}return context.checkPermission(permission, android.os.Process.myPid(), Process.myUid());}
2、ActivityCompat.requestPermissions()
/*** Requests permissions to be granted to this application. These permissions* must be requested in your manifest, they should not be granted to your app,* and they should have protection level {@link android.content.pm.PermissionInfo* #PROTECTION_DANGEROUS dangerous}, regardless whether they are declared by* the platform or a third-party app.* <p>* Normal permissions {@link android.content.pm.PermissionInfo#PROTECTION_NORMAL}* are granted at install time if requested in the manifest. Signature permissions* {@link android.content.pm.PermissionInfo#PROTECTION_SIGNATURE} are granted at* install time if requested in the manifest and the signature of your app matches* the signature of the app declaring the permissions.* </p>* <p>* If your app does not have the requested permissions the user will be presented* with UI for accepting them. After the user has accepted or rejected the* requested permissions you will receive a callback reporting whether the* permissions were granted or not. Your activity has to implement {@link* android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback}* and the results of permission requests will be delivered to its {@link* android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(* int, String[], int[])} method.* </p>* <p>* Note that requesting a permission does not guarantee it will be granted and* your app should be able to run without having this permission.* </p>* <p>* This method may start an activity allowing the user to choose which permissions* to grant and which to reject. Hence, you should be prepared that your activity* may be paused and resumed. Further, granting some permissions may require* a restart of you application. In such a case, the system will recreate the* activity stack before delivering the result to your onRequestPermissionsResult(* int, String[], int[]).* </p>* <p>* When checking whether you have a permission you should use {@link* #checkSelfPermission(android.content.Context, String)}.* </p>** @param activity The target activity.* @param permissions The requested permissions.* @param requestCode Application specific request code to match with a result* reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(* int, String[], int[])}.** @see #checkSelfPermission(android.content.Context, String)* @see #shouldShowRequestPermissionRationale(android.app.Activity, String)*/public static void requestPermissions(final @NonNull Activity activity,final @NonNull String[] permissions, final int requestCode) {if (Build.VERSION.SDK_INT >= 23) {ActivityCompatApi23.requestPermissions(activity, permissions, requestCode);} else if (activity instanceof OnRequestPermissionsResultCallback) {Handler handler = new Handler(Looper.getMainLooper());handler.post(new Runnable() {@Overridepublic void run() {final int[] grantResults = new int[permissions.length];PackageManager packageManager = activity.getPackageManager();String packageName = activity.getPackageName();final int permissionCount = permissions.length;for (int i = 0; i < permissionCount; i++) {grantResults[i] = packageManager.checkPermission(permissions[i], packageName);}((OnRequestPermissionsResultCallback) activity).onRequestPermissionsResult(requestCode, permissions, grantResults);}});}}
3、AppCompatActivity.onRequestPermissionsResult()?
該方法類似于Activity的OnActivityResult()的回調(diào)方法,主要接收請(qǐng)求授權(quán)的返回值
下面開始在項(xiàng)目中進(jìn)行權(quán)限封裝:?
1、新建一個(gè)BaseActivity活動(dòng),extends自AppCompatActivity。這里將權(quán)限申請(qǐng)?jiān)O(shè)計(jì)成基類,讓項(xiàng)目中的所有活動(dòng)都繼承BaseActivity類。?
延伸學(xué)習(xí):關(guān)于extends和implements的區(qū)別參考
2、聲明兩個(gè)Map類型的變量,用于存放取得權(quán)限后的運(yùn)行和未獲取權(quán)限時(shí)的運(yùn)行。?
延伸學(xué)習(xí):java中Map,List與Set的區(qū)別
* @param requestId 請(qǐng)求授權(quán)的Id,唯一即可* @param permission 請(qǐng)求的授權(quán)* @param allowableRunnable 同意授權(quán)后的操作* @param disallowableRunnable 禁止授權(quán)后的操作**/protected void requestPermission(int requestId, String permission,Runnable allowableRunnable, Runnable disallowableRunnable) {if (allowableRunnable == null) {throw new IllegalArgumentException("allowableRunnable == null");}allowablePermissionRunnables.put(requestId, allowableRunnable);if (disallowableRunnable != null) {disallowblePermissionRunnables.put(requestId, disallowableRunnable);}//版本判斷if (Build.VERSION.SDK_INT >= 23) {//檢查是否擁有權(quán)限int checkPermission = ContextCompat.checkSelfPermission(MyApplication.getContext(), permission);if (checkPermission != PackageManager.PERMISSION_GRANTED) {//彈出對(duì)話框請(qǐng)求授權(quán)ActivityCompat.requestPermissions(BaseActivity.this, new String[]{permission}, requestId);return;} else {allowableRunnable.run();}} else {allowableRunnable.run();}} 4、實(shí)現(xiàn)onRequestPermissionsResult方法。
@Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);if (grantResults[0] == PackageManager.PERMISSION_GRANTED){Runnable allowRun=allowablePermissionRunnables.get(requestCode);allowRun.run();}else {Runnable disallowRun = disallowblePermissionRunnables.get(requestCode);disallowRun.run();}} 5、調(diào)用
public static final String CONTACT_PERMISSION = android.Manifest.permission.READ_CONTACTS;public static final int readContactRequest = 1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.content_get_contacts);ContactsLv = (ListView) findViewById(R.id.ContactsLv);adapter = new ContactsAdapter(list, this);ContactsLv.setAdapter(adapter);requestPermission(readContactRequest, CONTACT_PERMISSION, new Runnable() {@Overridepublic void run() {getContacts();}}, new Runnable() {@Overridepublic void run() {getContactsDenied();}});}
總結(jié)
以上是生活随笔為你收集整理的Android之6.0 权限申请封装的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android之在ubuntu上常用的a
- 下一篇: Andorid之华为手机开发模式不打印日