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

Android 三種定位方式實作與比較

編輯:關於 Android 程式設計

近來研究了 Android 的定位方式,查閱了不少資料並實際拿手機測試,以下是我的整理。

Android 一共有三種定位方式:GPS 定位、網路定位,以及基於基站的定位。但不論採用哪一種,都需要開啟網路或 GPS。

首先在 Manifest 中加入權限:

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

其中 COARSE_LOCATION 用於基站定位,若缺少這個權限,在呼叫 getCellLocation() 時會報錯。

第一種:透過基站定位(Google 定位介面)

這種方式取得手機目前的基站資訊(Cell ID、LAC 等),再向 Google 的定位介面 POST 請求,換回經緯度:

public class LocationAct extends Activity {
    private TextView txtInfo;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button) findViewById(R.id.btnStart);
        txtInfo = (TextView) findViewById(R.id.txtInfo);
        btn.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View view) { getLocation(); }
        });
    }
    private void getLocation() {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        GsmCellLocation gsmCell = (GsmCellLocation) tm.getCellLocation();
        int cid = gsmCell.getCid();
        int lac = gsmCell.getLac();
        String netOperator = tm.getNetworkOperator();
        int mcc = Integer.valueOf(netOperator.substring(0, 3));
        int mnc = Integer.valueOf(netOperator.substring(3, 5));
        JSONObject holder = new JSONObject();
        JSONArray array = new JSONArray();
        JSONObject data = new JSONObject();
        try {
            holder.put("version", "1.1.0");
            holder.put("host", "maps.google.com");
            holder.put("address_language", "zh_CN");
            holder.put("request_address", true);
            holder.put("radio_type", "gsm");
            holder.put("carrier", "HTC");
            data.put("cell_id", cid);
            data.put("location_area_code", lac);
            data.put("mobile_country_code", mcc);
            data.put("mobile_network_code", mnc);
            array.put(data);
            holder.put("cell_towers", array);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("https://www.google.com/loc/json");
        try {
            httpPost.setEntity(new StringEntity(holder.toString()));
            HttpResponse httpResponse = client.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer stringBuffer = new StringBuffer();
            String result;
            while ((result = reader.readLine()) != null) {
                stringBuffer.append(result);
            }
            txtInfo.setText(stringBuffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

第二種:透過 GPS 定位

使用 LocationManager 指定 GPS_PROVIDER,並註冊位置與 GPS 狀態監聽器:

public class MainActivity extends Activity {
    private LocationManager locationManager;
    private GpsStatus gpsstatus;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        // 依 Criteria 取得最符合的 provider
        String currentProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
        Location currentLocation = locationManager.getLastKnownLocation(currentProvider);
        if (currentLocation == null) {
            locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener);
        }
        locationManager.addGpsStatusListener(gpsListener);
        // 每隔 10 秒取一次位置資訊
        while (true) {
            currentLocation = locationManager.getLastKnownLocation(currentProvider);
            if (currentLocation != null) {
                Log.d("Location", "Latitude: " + currentLocation.getLatitude());
                Log.d("Location", "location: " + currentLocation.getLongitude());
                break;
            } else {
                Log.d("Location", "Latitude: 0");
                Log.d("Location", "location: 0");
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                Log.e("Location", e.getMessage());
            }
        }
    }
    private GpsStatus.Listener gpsListener = new GpsStatus.Listener() {
        @Override
        public void onGpsStatusChanged(int event) {
            gpsstatus = locationManager.getGpsStatus(null);
            switch (event) {
                case GpsStatus.GPS_EVENT_FIRST_FIX: break;
                case GpsStatus.GPS_EVENT_STARTED: break;
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    // 可統計目前可見的衛星數量
                    int count = 0;
                    for (GpsSatellite s : gpsstatus.getSatellites()) { count++; }
                    Toast.makeText(MainActivity.this, "Satellite Count:" + count, Toast.LENGTH_SHORT).show();
                    break;
                case GpsStatus.GPS_EVENT_STOPPED:
                    Log.d("Location", "GPS_EVENT_STOPPED");
                    break;
            }
        }
    };
    private LocationListener locationListener = new LocationListener() {
        @Override public void onLocationChanged(Location location) { Log.d("Location", "onLocationChanged"); }
        @Override public void onProviderDisabled(String provider) { Log.d("Location", "onProviderDisabled"); }
        @Override public void onProviderEnabled(String provider) { Log.d("Location", "onProviderEnabled"); }
        @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Location", "onStatusChanged"); }
    };
}

第三種:透過網路(Criteria 自動挑選 provider)

以 Criteria 描述需求,交由系統挑選最合適的 provider,並可用 Geocoder 把座標反查成地址:

package com.test;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        criteria.setSpeedRequired(false);
        String currentProvider = locationManager.getBestProvider(criteria, true);
        Log.d("Location", "currentProvider: " + currentProvider);
        Location currentLocation = locationManager.getLastKnownLocation(currentProvider);
        if (currentLocation == null) {
            locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener);
        }
        while (true) {
            currentLocation = locationManager.getLastKnownLocation(currentProvider);
            if (currentLocation != null) {
                Log.d("Location", "Latitude: " + currentLocation.getLatitude());
                Log.d("Location", "location: " + currentLocation.getLongitude());
                break;
            } else {
                Log.d("Location", "Latitude: 0");
                Log.d("Location", "location: 0");
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                Log.e("Location", e.getMessage());
            }
        }
        // 解析地址並顯示
        Geocoder geoCoder = new Geocoder(this);
        try {
            int latitude = (int) currentLocation.getLatitude();
            int longitude = (int) currentLocation.getLongitude();
            List<Address> list = geoCoder.getFromLocation(latitude, longitude, 2);
            for (int i = 0; i < list.size(); i++) {
                Address address = list.get(i);
                Toast.makeText(MainActivity.this,
                        address.getCountryName() + address.getAdminArea() + address.getFeatureName(),
                        Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    private LocationListener locationListener = new LocationListener() {
        @Override public void onLocationChanged(Location location) { Log.d("Location", "onLocationChanged"); }
        @Override public void onProviderDisabled(String provider) { Log.d("Location", "onProviderDisabled"); }
        @Override public void onProviderEnabled(String provider) { Log.d("Location", "onProviderEnabled"); }
        @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Location", "onStatusChanged"); }
    };
}

三種方式各有取捨:GPS 精度最高但耗電、受環境影響;基站定位廣為覆蓋但精度較低;網路定位則在精度與功耗之間取得平衡,實務上常以 Criteria 交由系統自動挑選。

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