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

Android 檢測 GPS/網絡定位是否啟用:需分別判斷而非合併參數

     編輯:程式設計綜合問答

錯誤代碼


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 {
            // 定位被關閉,暫停定位並提示用戶
        }
    }
}

權限提醒

  • Manifest 需 ACCESS_FINE_LOCATION(GPS)與 ACCESS_COARSE_LOCATION(網絡)。
  • Android 10+ 需在前台服務或具備 ACCESS_BACKGROUND_LOCATION 才能背景定位。
  • Android 12+ 區分精確/模糊權限,請求時需說明用途。

分別檢查 GPS_PROVIDER 與 NETWORK_PROVIDER 是標準做法,切勿嘗試合併參數呼叫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved