Android6.0 許可權申請封裝
阿新 • • 發佈:2019-02-05
之前一篇部落格初試了Android6.0系統的動態許可權申請,成功之後開始思考將許可權申請功能封裝以供更加方便的呼叫。
查閱6.0系統許可權相關的API,整個許可權申請需要呼叫三個方法:
1. ContextCompat.checkSelfPermission()
檢查應用是否擁有該許可權,被授權返回值為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() {
@Override
public 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()的回撥方法,主要接收請求授權的返回值
下面開始在專案中進行許可權封裝:
1、新建一個BaseActivity活動,extends自AppCompatActivity。這裡將許可權申請設計成基類,讓專案中的所有活動都繼承BaseActivity類。
延伸學習:關於extends和implements的區別參考
2、宣告兩個Map型別的變數,用於存放取得許可權後的執行和未獲取許可權時的執行。
延伸學習:java中Map,List與Set的區別
private Map<Integer, Runnable> allowablePermissionRunnables = new HashMap<>();
private Map<Integer, Runnable> disallowblePermissionRunnables = new HashMap<>();
3、實現requesPermission方法。
/**
* @param requestId 請求授權的Id,唯一即可
* @param permission 請求的授權
* @param allowableRunnable 同意授權後的操作
* @param disallowableRunnable 禁止授權後的操作
**/
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) {
//檢查是否擁有許可權
int checkPermission = ContextCompat.checkSelfPermission(MyApplication.getContext(), permission);
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
//彈出對話方塊請求授權
ActivityCompat.requestPermissions(BaseActivity.this, new String[]{permission}, requestId);
return;
} else {
allowableRunnable.run();
}
} else {
allowableRunnable.run();
}
}
4、實現onRequestPermissionsResult方法。
@Override
public 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、呼叫
public static final String CONTACT_PERMISSION = android.Manifest.permission.READ_CONTACTS;
public static final int readContactRequest = 1;
@Override
protected 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() {
@Override
public void run() {
getContacts();
}
}, new Runnable() {
@Override
public void run() {
getContactsDenied();
}
});
}