if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)) { // ❌ 編譯錯誤:方法簽名只接受單一 String
...
}
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean netEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gpsEnabled || netEnabled) {
Toast.makeText(this, "GPS/網絡定位已啟用", Toast.LENGTH_SHORT).show();
// 可繼續請求定位
} else {
// 引導用戶開啟定位設定
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
public static boolean isLocationEnabled(Context context) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (lm == null) return false;
try {
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
return false;
}
}
// 註冊廣播接收器
// Receiver
public class LocationModeChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (isLocationEnabled(context)) {
// 定位已開啟,可恢復定位請求
} else {
// 定位被關閉,暫停定位並提示用戶
}
}
}
ACCESS_FINE_LOCATION(GPS)與 ACCESS_COARSE_LOCATION(網絡)。ACCESS_BACKGROUND_LOCATION 才能背景定位。分別檢查 GPS_PROVIDER 與 NETWORK_PROVIDER 是標準做法,切勿嘗試合併參數呼叫。