Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 監聽 GPS 狀態並跳轉系統設置頁

編輯:關於 Android 程式設計

在使用定位功能前,通常需要先檢測 GPS 是否已開啟,若未開啟則引導用戶前往系統設置頁開啟。

首先在清單文件中加入定位權限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

核心代碼如下:

/**
 * 監聽 GPS 狀態
 */
private void initGPS() {
    LocationManager locationManager = (LocationManager)
            this.getSystemService(Context.LOCATION_SERVICE);

    // 判斷 GPS 模塊是否開啟,若未開啟則引導用戶前往設置
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(TrainDetailsActivity.this, "請打開GPS", Toast.LENGTH_SHORT).show();
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("請打開GPS");
        dialog.setPositiveButton("確定", new android.content.DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // 跳轉到手機設置界面,由用戶手動開啟 GPS
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 0);
            }
        });
        dialog.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                arg0.dismiss();
            }
        });
        dialog.show();
    } else {
        // GPS 已開啟,可繼續後續定位邏輯
    }
}

關鍵在於透過 LocationManager.isProviderEnabled() 判斷 GPS 提供者是否可用,若不可用則用 Settings.ACTION_LOCATION_SOURCE_SETTINGS 這個系統意圖,一鍵跳轉到系統的位置信息設置頁,用戶開啟後即可返回原頁面繼續操作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved