推薦閱讀相關(guān)文章: Android M 新的運(yùn)行時(shí)權(quán)限開發(fā)者需要知道的一切
Android M運(yùn)行時(shí)權(quán)限是個(gè)啥東西
啥是運(yùn)行時(shí)權(quán)限呢金踪?Android M對(duì)權(quán)限管理系統(tǒng)進(jìn)行了改版,之前我們的App需要權(quán)限,只需在manifest中申明即可仅胞,用戶安裝后次坡,一切申明的權(quán)限都可來去自如的使用。但是Android M把權(quán)限管理做了加強(qiáng)處理腐芍,在manifest申明了集侯,在使用到相關(guān)功能時(shí),還需重新授權(quán)方可使用帜消。當(dāng)然棠枉,不是所有權(quán)限都需重新授權(quán),所以就把這些需要重新授權(quán)方可使用的權(quán)限稱之為運(yùn)行時(shí)權(quán)限泡挺。
運(yùn)行時(shí)權(quán)限的影響
運(yùn)行時(shí)權(quán)限的好處可以讓用戶使用時(shí)更有主動(dòng)權(quán)辈讶,不會(huì)讓app隨便亂來。
但是受害最深的卻是我們這些受苦受難的開發(fā)者娄猫,為何這么說呢贱除?如果你的app的targetSdkVersion 是23也就是android 6.0的話,遇到運(yùn)行時(shí)權(quán)限不去做代碼處理的話媳溺,程序直接崩掉月幌。
所以,如果你的app沒有在android 6.0上做足夠的測試悬蔽,請(qǐng)不要設(shè)置targetSdk為23扯躺,22以下就不會(huì)出現(xiàn)問題。
但是蝎困,作為開發(fā)者录语,我們還是必須要與時(shí)俱進(jìn)的不是,而且以后的主流機(jī)型也必然是android M禾乘,怎么能不去適配他/她呢澎埠?繼續(xù)往下看。
哪些是運(yùn)行時(shí)權(quán)限
要先做好適配始藕,那就必然要先了解哪些是運(yùn)行時(shí)權(quán)限蒲稳。
先看下哪些是不用特殊處理的權(quán)限,android稱之為普通權(quán)限:
參考鏈接:http://developer.android.com/guide/topics/security/normal-permissions.html
As of API level 23, the following permissions are classified as PROTECTION_NORMAL:
android.permission.ACCESS_LOCATION_EXTRA_COMMANDS
android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_NOTIFICATION_POLICY
android.permission.ACCESS_WIFI_STATE
android.permission.ACCESS_WIMAX_STATE
android.permission.BLUETOOTH
android.permission.BLUETOOTH_ADMIN
android.permission.BROADCAST_STICKY
android.permission.CHANGE_NETWORK_STATE
android.permission.CHANGE_WIFI_MULTICAST_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.CHANGE_WIMAX_STATE
android.permission.DISABLE_KEYGUARD
android.permission.EXPAND_STATUS_BAR
android.permission.FLASHLIGHT
android.permission.GET_ACCOUNTS
android.permission.GET_PACKAGE_SIZE
android.permission.INTERNET
android.permission.KILL_BACKGROUND_PROCESSES
android.permission.MODIFY_AUDIO_SETTINGS
android.permission.NFC
android.permission.READ_SYNC_SETTINGS
android.permission.READ_SYNC_STATS
android.permission.RECEIVE_BOOT_COMPLETED
android.permission.REORDER_TASKS
android.permission.REQUEST_INSTALL_PACKAGES
android.permission.SET_TIME_ZONE
android.permission.SET_WALLPAPER
android.permission.SET_WALLPAPER_HINTS
android.permission.SUBSCRIBED_FEEDS_READ
android.permission.TRANSMIT_IR
android.permission.USE_FINGERPRINT
android.permission.VIBRATE
android.permission.WAKE_LOCK
android.permission.WRITE_SYNC_SETTINGS
com.android.alarm.permission.SET_ALARM
com.android.launcher.permission.INSTALL_SHORTCUT
com.android.launcher.permission.UNINSTALL_SHORTCUT
再看下運(yùn)行時(shí)權(quán)限伍派,android稱之為危險(xiǎn)權(quán)限(google還對(duì)其分了組):
參考鏈接:http://developer.android.com/guide/topics/security/permissions.html#normal-dangerous
同一組的任何一個(gè)權(quán)限被授權(quán)了弟塞,其他權(quán)限也自動(dòng)被授權(quán)。例如拙已,一旦WRITE_CONTACTS被授權(quán)了决记,app也有READ_CONTACTS和GET_ACCOUNTS了。
------------------------------ 關(guān)鍵部分來了---------------------------------------------
代碼封裝
目前對(duì)運(yùn)行時(shí)權(quán)限倍踪,github上也有些代碼封裝庫系宫,但是都感覺用起來太麻煩索昂,于是自己動(dòng)手封裝了下:
參考代碼(google寫的sample):
https://github.com/googlesamples/android-RuntimePermissions;
http://developer.android.com/training/permissions/requesting.html
封裝代碼如下:
在BaseActivity添加如下代碼:
//**************** Android M Permission (Android 6.0權(quán)限控制代碼封裝)
*****************************************************
private int permissionRequestCode = 88;
private PermissionCallback permissionRunnable ;
public interface PermissionCallback{
void hasPermission();
void noPermission();
}
/**
* Android M運(yùn)行時(shí)權(quán)限請(qǐng)求封裝
* @param permissionDes 權(quán)限描述
* @param runnable 請(qǐng)求權(quán)限回調(diào)
* @param permissions 請(qǐng)求的權(quán)限(數(shù)組類型)扩借,直接從Manifest中讀取相應(yīng)的值椒惨,比如Manifest.permission.WRITE_CONTACTS
*/
public void performCodeWithPermission(@NonNull String permissionDes,PermissionCallback runnable,@NonNull String... permissions){
if(permissions == null || permissions.length == 0)return;
// this.permissionrequestCode = requestCode;
this.permissionRunnable = runnable;
if((Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || checkPermissionGranted(permissions)){
if(permissionRunnable!=null){
permissionRunnable.hasPermission();
permissionRunnable = null;
}
}else{
//permission has not been granted.
requestPermission(permissionDes,permissionRequestCode,permissions);
}
}
private boolean checkPermissionGranted(String[] permissions){
boolean flag = true;
for(String p:permissions){
if(ActivityCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED){
flag = false;
break;
}
}
return flag;
}
private void requestPermission(String permissionDes,final int requestCode,final String[] permissions){
if(shouldShowRequestPermissionRationale(permissions)){
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// For example, if the request has been denied previously.
// Snackbar.make(getWindow().getDecorView(), requestName,
// Snackbar.LENGTH_INDEFINITE)
// .setAction(R.string.common_ok, new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// ActivityCompat.requestPermissions(BaseAppCompatActivity.this,
// permissions,
// requestCode);
// }
// })
// .show();
//如果用戶之前拒絕過此權(quán)限,再提示一次準(zhǔn)備授權(quán)相關(guān)權(quán)限
new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage(permissionDes)
.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(BaseAppCompatActivity.this, permissions, requestCode);
}
}).show();
}else{
// Contact permissions have not been granted yet. Request them directly.
ActivityCompat.requestPermissions(BaseAppCompatActivity.this, permissions, requestCode);
}
}
private boolean shouldShowRequestPermissionRationale(String[] permissions){
boolean flag = false;
for(String p:permissions){
if (ActivityCompat.shouldShowRequestPermissionRationale(this,p)){
flag = true;
break;
}
}
return flag;
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if(requestCode == permissionRequestCode){
if(verifyPermissions(grantResults)){
if(permissionRunnable!=null) {
permissionRunnable.hasPermission();
permissionRunnable = null;
}
}else{
showToast("暫無權(quán)限執(zhí)行相關(guān)操作潮罪!");
if(permissionRunnable!=null) {
permissionRunnable.noPermission();
permissionRunnable = null;
}
}
}else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public boolean verifyPermissions(int[] grantResults) {
// At least one result must be checked.
if(grantResults.length < 1){
return false;
}
// Verify that each required permission has been granted, otherwise return false.
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
//********************** END Android M Permission ****************************************
Tips:
1)BaseActivity要繼承AppCompatActivity
2)support包使用盡量新的康谆,我使用的是compile 'com.android.support:appcompat-v7:23.0.1' 以防里面的ActivityCompat找不到相關(guān)類或方法。
3)如果在Fragment中使用嫉到,直接在自己的BaseFragment寫個(gè)方法調(diào)用此Activity的方法即可沃暗。
/**
* Android M運(yùn)行時(shí)權(quán)限請(qǐng)求封裝
* @param permissionDes 權(quán)限描述
* @param runnable 請(qǐng)求權(quán)限回調(diào)
* @param permissions 請(qǐng)求的權(quán)限(數(shù)組類型),直接從Manifest中讀取相應(yīng)的值何恶,比如Manifest.permission.WRITE_CONTACTS
*/
public void performCodeWithPermission(@NonNull String permissionDes,BaseAppCompatActivity.PermissionCallback runnable,@NonNull String... permissions){
if(getActivity()!=null && getActivity() instanceof BaseAppCompatActivity){
((BaseAppCompatActivity) getActivity()).performCodeWithPermission(permissionDes,runnable,permissions);
}
}
一句代碼使用:
比如孽锥,我們要請(qǐng)求相機(jī):
performCodeWithPermission("XX App請(qǐng)求訪問相機(jī)權(quán)限",new BaseAppCompatActivity.PermissionCallback() {
@Override
public void hasPermission() {
//執(zhí)行打開相機(jī)相關(guān)代碼
}
@Override
public void noPermission() {
}
}, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE);
寫在最后
- 如果讀者還是沒有看過文章開頭推薦的文章,建議先看一遍细层,有些知識(shí)和出現(xiàn)問題的場景此文沒有細(xì)說惜辑,看完后對(duì)運(yùn)行時(shí)權(quán)限會(huì)有更好的理解。
- 另外疫赎,如果本文有描述不對(duì)之處盛撑,還望大家多多指正,多謝捧搞!
===20160509更新========
checkSelfPermission檢測權(quán)限失效問題
要改成如下的檢測方案:
參考:http://stackoverflow.com/questions/33407250/checkselfpermission-method-is-not-working-in-targetsdkversion-22
public boolean selfPermissionGranted(String permission) {
// For Android < Android M, self permissions are always granted.
boolean result = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (targetSdkVersion >= Build.VERSION_CODES.M) {
// targetSdkVersion >= Android M, we can
// use Context#checkSelfPermission
result = context.checkSelfPermission(permission)
== PackageManager.PERMISSION_GRANTED;
} else {
// targetSdkVersion < Android M, we have to use PermissionChecker
result = PermissionChecker.checkSelfPermission(context, permission)
== PermissionChecker.PERMISSION_GRANTED;
}
}
return result;
}
獲取target sdk的方法如下:
try {
final PackageInfo info = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
targetSdkVersion = info.applicationInfo.targetSdkVersion;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
官方解決方案 EasyPermissions
google自己出了一個(gè)解決方案撵彻,在github上叫easypermissions。
鏈接為:https://github.com/googlesamples/easypermissions
【原創(chuàng)文章实牡,轉(zhuǎn)載請(qǐng)注明出處】