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

Android 基礎入門教程 10.14:GPS 定位入門實戰

編輯:關於 Android 程式設計

一、定位相關的核心 API

1)LocationManager

它是系統服務,不能直接 new:

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

並且別忘了申請定位權限:

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

拿到實例後,常用的方法有這些:

  • addGpsStatusListener(GpsStatus.Listener):註冊 GPS 狀態監聽。
  • addProximityAlert(lat, lng, radius, expiration, intent):添加臨近警告。
  • getAllProviders():返回所有 LocationProvider。
  • getBestProvider(Criteria, boolean):按條件取最優 Provider。
  • getGpsStatus(GpsStatus):獲取 GPS 狀態。
  • getLastKnownLocation(String provider):取指定 Provider 最近一次已知位置。
  • getProvider(String name) / getProviders(...):按名稱或條件取 Provider。
  • isProviderEnabled(String provider):判斷某 Provider 是否可用。
  • removeGpsStatusListener(...) / removeProximityAlert(...):移除監聽與警告。
  • requestLocationUpdates(...):週期性獲取定位,兩個重載分別以 PendingIntent 和 LocationListener 接收結果。

2)LocationProvider

它是定位方式的抽象表示,能查詢精度、名稱、耗電需求、是否收費,以及是否需要基站、網絡、衛星,是否支持海拔、方位、速度等信息。

3)Location

位置信息本體,常用取值方法:getAccuracy()、getAltitude()、getBearing()、getLatitude()、getLongitude()、getProvider()、getSpeed(),以及 hasAccuracy() 這類存在性判斷。

4)Criteria

取 Provider 時的篩選條件類:setAccuracy()、setAltitudeRequired()、setBearingRequired()、setCostAllowed()、setPowerRequirement()、setSpeedRequired()。

二、列出可用的 LocationProvider

可以看到設備上通常有三個 Provider:

  • passive:由其他應用代為提供;
  • gps:衛星定位;
  • network:網絡定位。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_one, btn_two, btn_three;
    private TextView tv_result;
    private LocationManager lm;
    private List<String> pNames = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        btn_one = findViewById(R.id.btn_one);
        btn_two = findViewById(R.id.btn_two);
        btn_three = findViewById(R.id.btn_three);
        tv_result = findViewById(R.id.tv_result);
        btn_one.setOnClickListener(this);
        btn_two.setOnClickListener(this);
        btn_three.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_one: // 全部
                pNames.clear();
                pNames = lm.getAllProviders();
                break;
            case R.id.btn_two: // 按條件篩選
                pNames.clear();
                Criteria criteria = new Criteria();
                criteria.setCostAllowed(false);      // 免費
                criteria.setAltitudeRequired(true);  // 能提供海拔
                criteria.setBearingRequired(true);   // 能提供方位
                pNames = lm.getProviders(criteria, true);
                break;
            case R.id.btn_three: // 指定名稱
                pNames.clear();
                pNames.add(lm.getProvider(LocationManager.GPS_PROVIDER).getName());
                break;
        }
        tv_result.setText(getProvider());
    }

    private String getProvider() {
        StringBuilder sb = new StringBuilder();
        for (String s : pNames) {
            sb.append(s).append("\n");
        }
        return sb.toString();
    }
}

三、判斷並開啟 GPS

定位前的第一件事,是確認 GPS 是否可用(這裡暫不討論 AGPS)。

private boolean isGpsAble(LocationManager lm) {
    return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

若未開啟,有兩種處理方式:

方式一:直接幫用戶打開(僅 Android 5.0 之前有效)

// 強制打開 GPS,5.0 以後失效
private void openGPS(Context context) {
    Intent gpsIntent = new Intent();
    gpsIntent.setClassName("com.android.settings",
            "com.android.settings.widget.SettingsAppWidgetProvider");
    gpsIntent.addCategory(Intent.CATEGORY_ALTERNATIVE);
    gpsIntent.setData(Uri.parse("custom:3"));
    try {
        PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();
    } catch (PendingIntent.CanceledException e) {
        e.printStackTrace();
    }
}

方式二:跳轉系統設置頁,讓用戶自己開(推薦)

private void openGPS2() {
    startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}

四、動態獲取位置

思路很簡單:調用 requestLocationUpdates 掛一個 LocationListener 即可。

public class LocationActivity extends AppCompatActivity {

    private LocationManager lm;
    private TextView tv_show;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        tv_show = findViewById(R.id.tv_show);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!isGpsAble(lm)) {
            Toast.makeText(this, "請打開GPS~", Toast.LENGTH_SHORT).show();
            openGPS2();
        }

        // 先取一次最近位置
        updateShow(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER));

        // 每 2 秒、位移 8 米更新一次
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateShow(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) { }

            @Override
            public void onProviderEnabled(String provider) {
                updateShow(lm.getLastKnownLocation(provider));
            }

            @Override
            public void onProviderDisabled(String provider) {
                updateShow(null);
            }
        });
    }

    private void updateShow(Location location) {
        if (location == null) {
            tv_show.setText("");
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("當前位置信息:\n");
        sb.append("經度:" + location.getLongitude() + "\n");
        sb.append("緯度:" + location.getLatitude() + "\n");
        sb.append("海拔:" + location.getAltitude() + "\n");
        sb.append("速度:" + location.getSpeed() + "\n");
        sb.append("方向:" + location.getBearing() + "\n");
        sb.append("精度:" + location.getAccuracy() + "\n");
        tv_show.setText(sb.toString());
    }
}

GPS 需要室外天空視野,於是趁機出門買了杯奶茶順道截圖:

關於 requestLocationUpdates(provider, minTime, minDistance, listener):當時間超過 minTime(毫秒)或位移超過 minDistance(米)時回調。minTime 建議不低於 60000(1 分鐘),更省電;若追求實時,兩者都可以給 0,但要清楚這會顯著增加功耗。

五、臨近警告(地理圍欄)

固定一個圓心,當設備進入或離開指定半徑時觸發相應處理:

addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent)

其中 expiration 為過期時間(-1 表示永不過期),intent 指定觸發時要送達的組件。

public class ProximityActivity extends AppCompatActivity {

    private LocationManager lm;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_proximity);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        double longitude = 113.56843;
        double latitude = 22.374937;
        float radius = 10; // 單位:米

        Intent intent = new Intent(this, ProximityReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, -1, intent, 0);
        lm.addProximityAlert(latitude, longitude, radius, -1, pi);
    }
}

配套的廣播接收者:

public class ProximityReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean isEnter = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false);
        Toast.makeText(context, isEnter ? "你已到達南軟B1棟附近" : "你已離開南軟B1棟附近",
                Toast.LENGTH_LONG).show();
    }
}

記得在清單文件中註冊 <receiver android:name=".ProximityReceiver" />。

實測時把半徑設成了 10 米,結果從 B1 走到 D1 都還沒觸發,只好冒雨多走兩圈……

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