首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 檢查 GPS 與網絡定位提供者是否啟用的標準方法

     編輯:程式設計綜合問答

核心 API

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();
    }
}

權限前置檢查(Android 6.0+)

調用 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;
}
// 權限已授予,繼續檢查提供者狀態...

現代替代方案:FusedLocationProviderClient

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,簡化提供者管理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved