App 使用百度地圖定位 SDK,需在用戶拒絕定位權限時引導開啟。嘗試 PackageManager.checkPermission 失效(只要清單聲明即返回 true);try-catch 捕獲不到異常;BDLocationListener.onReceiveLocation 也不回調。
onReceiveLocation,導致調用方無感知。// 在啟動定位前檢查
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// 無權限,請求權限或引導用戶
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQ_LOC);
return;
}
mLocationClient.start();
public class MyApplication extends Application {
public static BDLocation lastLocation = null;
}
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
MyApplication.lastLocation = location; // 成功時更新
}
}
// 業務使用定位時
if (MyApplication.lastLocation == null ||
MyApplication.lastLocation.getLocType() == BDLocation.TypeServerError) {
// 定位失敗(含權限拒絕),引導用戶
showPermissionGuideDialog();
}
OnRequestPermissionsResult 回調@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQ_LOC) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationClient.start();
} else {
// 用戶拒絕,引導去設置頁
showGoToSettingsDialog();
}
}
}
ContextCompat.checkSelfPermission 而非 PackageManager.checkPermission。BDLocation 實例,null 視為失敗。Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
百度定位 SDK 權限拒絕無直接回調,需結合「運行時權限預檢」+「全局 Location 兜底判斷」+「請求權限結果回調」三重機制,確保在任何情況下都能感知並引導用戶授權。