原因:LocationClient 初始化位置錯誤,代碼放在 onDestroy() 中,導致定位服務未啟動即銷毀。
修正:在 onCreate() 或 onStart() 初始化並啟動:
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(myListener);
mLocationClient.start();
將啟動定位代碼移至 onCreate() 或 onResume():
@Override
protected void onResume() {
super.onResume();
if (mLocationClient != null && !mLocationClient.isStarted()) {
mLocationClient.start();
}
}
不能。Android 6.0+ 強制運行時權限,用戶必須手動授權。Google Play 政策禁止靜默獲取敏感權限。
正確做法:
onRequestPermissionsResult 處理授權結果。try-catch 包裹定位啟動代碼,捕獲 SecurityException,提示用戶去設置頁面手動開啟。Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)。AndroidManifest.xml 聲明 ACCESS_FINE_LOCATION、ACCESS_COARSE_LOCATION、INTERNET、READ_PHONE_STATE。meta-data 配置 com.baidu.lbsapi.API_KEY。<service android:name="com.baidu.location.f" />。