LocationManager 提供 isProviderEnabled(String provider) 方法,傳入常量即可檢查:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 檢查 GPS 提供者
boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// 檢查網絡定位提供者
boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.d("LOCATION", "GPS: " + gpsEnabled + ", Network: " + networkEnabled);
public void checkAndPromptLocationEnabled() {
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean gps = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gps && !network) {
new AlertDialog.Builder(this)
.setTitle("定位服務未開啟")
.setMessage("請開啟 GPS 或網絡定位以獲取位置信息")
.setPositiveButton("去設置", (dialog, which) -> {
// 跳轉到系統定位設置頁面
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
})
.setNegativeButton("取消", null)
.show();
}
}
調用 isProviderEnabled 無需權限,但後續請求位置更新需:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_LOCATION_PERMISSION);
return;
}
// 權限已授予,繼續檢查提供者狀態...
Google Play Services 提供的 FusedLocationProviderClient 封裝了提供者選擇邏輯,自動優選可用源:
FusedLocationProviderClient fused = LocationServices.getFusedLocationProviderClient(this);
fused.getLastLocation()
.addOnSuccessListener(location -> {
if (location != null) {
// 直接使用位置,無需手動判斷 GPS/Network
}
});
LocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER/NETWORK_PROVIDER) 直接檢查。Settings.ACTION_LOCATION_SOURCE_SETTINGS。FusedLocationProviderClient,簡化提供者管理。