今天遇到了個問題,其實原來也遇到過,但是好長時間沒有碰到了,有些遺忘。今天正好有點空,特整理下申請流程
權限動態申請流程:
1、檢查是否獲取該權限
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
檢查後會返回響應值,如果未授予需要我們手動申請
2、申請權限/先彈框解釋在申請
final String[] pers = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
requestPermissions(pers, LOCATION);
因爲我們產品定的流程是先彈自己的dialog框解釋,用戶點了確定再去請求,所以我多了一步就是彈了個框。
3、獲取結果,做下一步處理
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION) {
ArrayList<String> deniedPermissionList = new ArrayList();
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
deniedPermissionList.add(permissions[i]);
}
}
if (deniedPermissionList.isEmpty()) {
//已經全部授權
startLocation();
} else {
//勾選了對話框中”Don’t ask again”的選項, 返回false
for (String deniedPermission : deniedPermissionList) {
boolean flag = shouldShowRequestPermissionRationale(deniedPermission);
if (!flag) {
// todo 拒絕授權並打了勾不再提示
goSystemSettingPage();
return;
}
}
//拒絕授權
checkLocationPermission();
}
}
}
這裏有兩種情況:1、用戶點了拒絕了但未勾選下次不再提醒
2、用戶點了拒絕並且勾選了下次不再提醒
我的處理是,當第一種情況時,再次彈起解釋框讓用戶授權,第二種時跳轉系統設置頁面(因爲在申請系統就不能再調起系統授權框了),這樣可能比較暴力,但也沒什麼好辦法,接的別人的老代碼,裏邊有20多處調用接口都用到了經緯度。
遇到的坑:
1、一部分手機關閉gps也沒關係,可以通過基站定位到位置,但比較新版本的手機關閉了系統位置信息服務那就gg了,所以還要做相關處理
/**
* 處理關閉系統定位服務
*/
private boolean dealNoSysytemLocationPermission() {
boolean locationEnabled = CheckPermissionLocation.INSTANCE.isLocationEnabled(this.getApplicationContext());
if (!locationEnabled) { // 用戶關閉了系統定位服務
// 跳轉開啓系統定位頁面
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
return true;
}
return false;
}
2、部分相對低端的手機拒絕了權限後在check的時候一樣會返回true告訴你你的app已經有了該權限,這個比較噁心,比如我測到的紅米部分手機和vivo部分手機都是這樣,這就沒辦法了,還想要獲取到該權限,我這邊是這麼做的。先定位,如果定位失敗了直接跳轉系統頁讓用戶自己開啓我們app的定位權限
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
try {
this.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
後續:
我獲取把代碼替換了,簡單調研了下github上的權限申請庫,RxPermission、google自己的easypermissions和PermissionDispatcher。用戶原理各有特點但大同小異,這裏就不贅述了。個人還是比較喜歡最後一個,所以用了它,大家可以自行選擇