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

Android 基站定位實作(二):單基站定位完整流程

編輯:關於 Android 程式設計

基站定位的原理是:先透過手機訊號取得基站資訊,再呼叫第三方公開 API,依基站資訊查詢對應的經緯度與地址(約略位置)。本文將完整示範單基站定位的實作流程。

一、透過手機訊號取得基站資訊

利用 TelephonyManager 可取得 MCC(行動國家代碼)、MNC(行動網路代碼)以及 LAC、CID 等基站參數:

TelephonyManager mTelephonyManager =
    (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

// 回傳值為 MCC + MNC
String operator = mTelephonyManager.getNetworkOperator();
mcc = Integer.parseInt(operator.substring(0, 3));
mnc = Integer.parseInt(operator.substring(3));

// 中國移動與中國聯通取得 LAC、CID 的方式
GsmCellLocation location = (GsmCellLocation) mTelephonyManager.getCellLocation();
lac = location.getLac();
cid = location.getCid();

Log.i(TAG, "MCC = " + mcc + "\t MNC = " + mnc + "\t LAC = " + lac + "\t CID = " + cid);

二、呼叫第三方公開 API 查詢經緯度

取得基站資訊後,需將其組裝成 JSON 格式的請求參數:

private String getJsonCellPos(int mcc, int mnc, int lac, int cid) throws JSONException {
    JSONObject jsonCellPos = new JSONObject();
    jsonCellPos.put("version", "1.1.0");
    jsonCellPos.put("host", "maps.google.com");

    JSONArray array = new JSONArray();
    JSONObject json1 = new JSONObject();
    json1.put("location_area_code", "" + lac + "");
    json1.put("mobile_country_code", "" + mcc + "");
    json1.put("mobile_network_code", "" + mnc + "");
    json1.put("age", 0);
    json1.put("cell_id", "" + cid + "");
    array.put(json1);

    jsonCellPos.put("cell_towers", array);
    return jsonCellPos.toString();
}

接著以 HTTP POST 方式發送請求。這裡使用 HttpURLConnection 建立連線,設定適當的 Header(如 Content-Type、User-Agent 等),寫入請求內容後讀取回應:

public String httpPost(String url, String jsonCellPos) throws IOException {
    byte[] data = jsonCellPos.toString().getBytes();
    URL realUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
    conn.setConnectTimeout(6 * 1000);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(data);
    outStream.flush();
    outStream.close();

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream inputStream = conn.getInputStream();
        return new String(read(inputStream));
    }
    return null;
}

其中讀取串流的輔助方法如下:

public byte[] read(InputStream inputSream) throws IOException {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    int len = -1;
    byte[] buffer = new byte[1024];
    while ((len = inputSream.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    inputSream.close();
    return outStream.toByteArray();
}

三、請求與回應的 JSON 格式

請求的 JSON 參數大致如下:

{
  "cell_towers": [
    {
      "mobile_network_code": "1",
      "location_area_code": "43018",
      "cell_id": "11152773",
      "age": 0,
      "mobile_country_code": "460"
    }
  ],
  "host": "maps.google.com",
  "version": "1.1.0"
}

回應則包含經緯度與地址資訊:

{
  "location": {
    "latitude": "31.211389541625977",
    "longitude": "121.60332489013672",
    "address": {
      "city": "上海市浦東新區居裡路432號...",
      "country": "", "country_code": "", "county": "",
      "postal_code": "", "region": "", "street": "", "street_number": ""
    }
  },
  "access_token": "dummytoken"
}

四、權限設定

由於涉及定位與網路請求,需在 AndroidManifest.xml 中加入以下權限:

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

實作時,取得基站資訊與網路請求應放在背景執行緒中進行(如 new Thread()),避免阻塞主執行緒(UI 執行緒)。完成後即可解析回傳的 JSON,取得裝置所在的大致經緯度與地址。

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