一路學下來,我對 Android 的開發流程已經有了整體概念。為了增加一點實作的樂趣,這一篇就來動手寫一個簡單的基站定位程式。近來 LBS(Location Based Service,基於位置的服務)類型的行動應用相當火紅,像是微信、街旁等等,而基站定位正是這類應用的關鍵技術之一,就讓我們一起揭開它的面紗。
這一篇會用到事件處理、TelephonyManager、HTTP 通訊、JSON 解析等幾個重點知識。
在 Android 平台上,基站定位其實並不複雜,整體步驟是這樣的:
先呼叫 SDK 提供的 API(TelephonyManager)取得 MCC、MNC、LAC、CID 等資訊,接著透過 Google 的 API 換算出所在的經緯度,最後再借助 Google Map 的 API 取得實際的地理位置。
可能有朋友會問:MNC、MCC、LAC、CID 到底是什麼?Google 又是怎麼靠這些資料換算出經緯度的呢?
先來認識這幾個名詞:
MCC,Mobile Country Code,行動國家代碼(台灣為 466);
MNC,Mobile Network Code,行動網路代碼;
LAC,Location Area Code,位置區域碼;
CID,Cell Identity,基站編號,是個 16 位的數值(範圍 0 到 65535)。
搞懂這幾個名詞,聰明的朋友應該已經猜到後面的做法了:Google 資料庫裡存了這些對應關係,直接查詢就能換算出經緯度。至於 Google 是怎麼蒐集到電信業者基站資料的,就不得而知了,反正人家免費提供介面,我們直接呼叫即可。
我們沿用上一節的專案,在 DemoActivity 的介面上完成這個功能。先把 DemoActivity 使用的版面配置改一改:

第 1 行為 TextView,用來顯示提示文字;第 2 行為一個 Button,用來觸發事件;第 3、4 行分別用來顯示基站資訊與地理位置(目前為空,看不到內容)。
layout/main.xml 的內容如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Please click the button below to get your location" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" /> <TextView android:id="@+id/cellText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> <TextView android:id="@+id/lacationText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> </LinearLayout>
接著打開 DemoActivity.java 開始寫程式。
我們在 Activity 建立時就綁定事件,把下面的程式碼加到 setContentView(R.layout.main); 之後:
/** 為按鈕綁定事件 */ Button btnGetLocation = (Button)findViewById(R.id.button1); btnGetLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub onBtnClick(); } });
同時別忘了在檔頭 import 相關元件:
import android.view.View; import android.widget.Button; import android.view.View.OnClickListener;
簡單分析一下這段程式碼:先透過 findViewById(R.id.button1) 抓到按鈕物件,前面加上 (Button) 是把回傳值強制轉型成 Button;接著註冊點擊事件的監聽器,參數為 OnClickListener 物件,再覆寫它的 onClick 方法,在裡面呼叫我們自己寫的 onBtnClick(這個方法會在點擊時被觸發)。
觸發方法搭好之後,接下來就是實作它「被呼叫時要做什麼」。動手之前先在腦中把思路理清,是個好習慣。我們在 DemoActivity 類別裡加入以下幾個私有方法:
先把方法骨架搭好,完整程式碼如下:
package com.android.demo; import android.R.bool; import android.R.integer; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.view.View.OnClickListener; public class DemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** 為按鈕綁定事件 */ Button btnGetLocation = (Button)findViewById(R.id.button1); btnGetLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub onBtnClick(); } }); } /** 基站信息結構體 */ public class SCell{ public int MCC; public int MNC; public int LAC; public int CID; } /** 經緯度信息結構體 */ public class SItude{ public String latitude; public String longitude; } /** 按鈕點擊回調函數 */ private void onBtnClick(){ } /** 獲取基站信息 */ private SCell getCellInfo(){ } /** 獲取經緯度 */ private SItude getItude(SCell cell){ } /** 獲取地理位置 */ private String getLocation(SItude itude){ } /** 顯示結果 */ private void showResult(SCell cell, String location){ } }
接著在 onBtnClick 裡依序呼叫後面幾個方法:
/** 按鈕點擊回調函數 */ private void onBtnClick(){ /** 彈出一個等待狀態的框 */ ProgressDialog mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("正在獲取中..."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.show(); try { /** 獲取基站數據 */ SCell cell = getCellInfo(); /** 根據基站數據獲取經緯度 */ SItude itude = getItude(cell); /** 獲取地理位置 */ String location = getLocation(itude); /** 顯示結果 */ showResult(cell, location); /** 關閉對話框 */ mProgressDialog.dismiss(); }catch (Exception e) { /** 關閉對話框 */ mProgressDialog.dismiss(); /** 顯示錯誤 */ TextView cellText = (TextView)findViewById(R.id.cellText); cellText.setText(e.getMessage()); } }
按鈕相關的處理就完成了,接下來寫取得基站資訊的方法。
這一步要呼叫 SDK 的 TelephonyManager,記得在檔頭引入:
import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation;
完整程式碼如下:
/** * 獲取基站信息 * * @throws Exception */ private SCell getCellInfo() throws Exception { SCell cell = new SCell(); /** 調用API獲取基站信息 */ TelephonyManager mTelNet = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); GsmCellLocation location = (GsmCellLocation) mTelNet.getCellLocation(); if (location == null) throw new Exception("獲取基站信息失敗"); String operator = mTelNet.getNetworkOperator(); int mcc = Integer.parseInt(operator.substring(0, 3)); int mnc = Integer.parseInt(operator.substring(3)); int cid = location.getCid(); int lac = location.getLac(); /** 將獲得的數據放到結構體中 */ cell.MCC = mcc; cell.MNC = mnc; cell.LAC = lac; cell.CID = cid; return cell; }
若取到的位置資訊為 null,就拋出錯誤並中止後續流程;否則把基站資訊封裝成結構體回傳。
這一步要用 HTTP 呼叫 Google 的 API 來換算基站所在的經緯度。Android 作為一款聯網手機,網路功能不可或缺,平台提供了多個介面,這裡我們用 DefaultHttpClient。
完整方法程式碼如下:
/** * 獲取經緯度 * * @throws Exception */ private SItude getItude(SCell cell) throws Exception { SItude itude = new SItude(); /** 采用Android默認的HttpClient */ HttpClient client = new DefaultHttpClient(); /** 采用POST方法 */ HttpPost post = new HttpPost("https://www.google.com/loc/json"); try { /** 構造POST的JSON數據 */ JSONObject holder = new JSONObject(); 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"); JSONObject tower = new JSONObject(); tower.put("mobile_country_code", cell.MCC); tower.put("mobile_network_code", cell.MNC); tower.put("cell_id", cell.CID); tower.put("location_area_code", cell.LAC); JSONArray towerarray = new JSONArray(); towerarray.put(tower); holder.put("cell_towers", towerarray); StringEntity query = new StringEntity(holder.toString()); post.setEntity(query); /** 發出POST數據並獲取返回數據 */ HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer strBuff = new StringBuffer(); String result = null; while ((result = buffReader.readLine()) != null) { strBuff.append(result); } /** 解析返回的JSON數據獲得經緯度 */ JSONObject json = new JSONObject(strBuff.toString()); JSONObject subjosn = new JSONObject(json.getString("location")); itude.latitude = subjosn.getString("latitude"); itude.longitude = subjosn.getString("longitude"); Log.i("Itude", itude.latitude + itude.longitude); } catch (Exception e) { Log.e(e.getMessage(), e.toString()); throw new Exception("獲取經緯度出現錯誤:"+e.getMessage()); } finally{ post.abort(); client = null; } return itude; }
這裡用 POST 把 JSON 資料送到 Google API,對方回傳 JSON,我們解析後就能拿到經緯度。
拿到經緯度後,接著把它轉換成實體地址。這次改用 GET 方法呼叫 Google 地圖 API:
/** * 獲取地理位置 * * @throws Exception */ private String getLocation(SItude itude) throws Exception { String resultString = ""; /** 這裡采用get方法,直接將參數加到URL上 */ String urlString = String.format("https://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s", itude.latitude, itude.longitude); Log.i("URL", urlString); /** 新建HttpClient */ HttpClient client = new DefaultHttpClient(); /** 采用GET方法 */ HttpGet get = new HttpGet(urlString); try { /** 發起GET請求並獲得返回數據 */ HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer strBuff = new StringBuffer(); String result = null; while ((result = buffReader.readLine()) != null) { strBuff.append(result); } resultString = strBuff.toString(); /** 解析JSON數據,獲得物理地址 */ if (resultString != null && resultString.length() > 0) { JSONObject jsonobject = new JSONObject(resultString); JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString()); resultString = ""; for (int i = 0; i < jsonArray.length(); i++) { resultString = jsonArray.getJSONObject(i).getString("address"); } } } catch (Exception e) { throw new Exception("獲取物理位置出現錯誤:" + e.getMessage()); } finally { get.abort(); client = null; } return resultString; }
GET 方法比 POST 簡單多了,回傳的資料同樣是 JSON,解析一下就能取得實體地址。
資料都到手了,把它顯示出來即可:
/** 顯示結果 */ private void showResult(SCell cell, String location) { TextView cellText = (TextView) findViewById(R.id.cellText); cellText.setText(String.format("基站信息:mcc:%d, mnc:%d, lac:%d, cid:%d", cell.MCC, cell.MNC, cell.LAC, cell.CID)); TextView locationText = (TextView) findViewById(R.id.lacationText); locationText.setText("物理位置:" + location); }
編碼部分到這裡就完成了。上面有些地方漏了 import,這裡把完整程式碼一次貼出:
package com.android.demo; import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.view.View.OnClickListener; public class DemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** 為按鈕綁定事件 */ Button btnGetLocation = (Button) findViewById(R.id.button1); btnGetLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub onBtnClick(); } }); } /** 基站信息結構體 */ public class SCell{ public int MCC; public int MNC; public int LAC; public int CID; } /** 經緯度信息結構體 */ public class SItude{ public String latitude; public String longitude; } /** 按鈕點擊回調函數 */ private void onBtnClick() { /** 彈出一個等待狀態的框 */ ProgressDialog mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("正在獲取中..."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.show(); try { /** 獲取基站數據 */ SCell cell = getCellInfo(); /** 根據基站數據獲取經緯度 */ SItude itude = getItude(cell); /** 獲取地理位置 */ String location = getLocation(itude); /** 顯示結果 */ showResult(cell, location); /** 關閉對話框 */ mProgressDialog.dismiss(); } catch (Exception e) { /** 關閉對話框 */ mProgressDialog.dismiss(); /** 顯示錯誤 */ TextView cellText = (TextView) findViewById(R.id.cellText); cellText.setText(e.getMessage()); Log.e("Error", e.getMessage()); } } /** * 獲取基站信息 * * @throws Exception */ private SCell getCellInfo() throws Exception { SCell cell = new SCell(); /** 調用API獲取基站信息 */ TelephonyManager mTelNet = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); GsmCellLocation location = (GsmCellLocation) mTelNet.getCellLocation(); if (location == null) throw new Exception("獲取基站信息失敗"); String operator = mTelNet.getNetworkOperator(); int mcc = Integer.parseInt(operator.substring(0, 3)); int mnc = Integer.parseInt(operator.substring(3)); int cid = location.getCid(); int lac = location.getLac(); /** 將獲得的數據放到結構體中 */ cell.MCC = mcc; cell.MNC = mnc; cell.LAC = lac; cell.CID = cid; return cell; } /** * 獲取經緯度 * * @throws Exception */ private SItude getItude(SCell cell) throws Exception { SItude itude = new SItude(); /** 采用Android默認的HttpClient */ HttpClient client = new DefaultHttpClient(); /** 采用POST方法 */ HttpPost post = new HttpPost("https://www.google.com/loc/json"); try { /** 構造POST的JSON數據 */ JSONObject holder = new JSONObject(); 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"); JSONObject tower = new JSONObject(); tower.put("mobile_country_code", cell.MCC); tower.put("mobile_network_code", cell.MNC); tower.put("cell_id", cell.CID); tower.put("location_area_code", cell.LAC); JSONArray towerarray = new JSONArray(); towerarray.put(tower); holder.put("cell_towers", towerarray); StringEntity query = new StringEntity(holder.toString()); post.setEntity(query); /** 發出POST數據並獲取返回數據 */ HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer strBuff = new StringBuffer(); String result = null; while ((result = buffReader.readLine()) != null) { strBuff.append(result); } /** 解析返回的JSON數據獲得經緯度 */ JSONObject json = new JSONObject(strBuff.toString()); JSONObject subjosn = new JSONObject(json.getString("location")); itude.latitude = subjosn.getString("latitude"); itude.longitude = subjosn.getString("longitude"); Log.i("Itude", itude.latitude + itude.longitude); } catch (Exception e) { Log.e(e.getMessage(), e.toString()); throw new Exception("獲取經緯度出現錯誤:"+e.getMessage()); } finally{ post.abort(); client = null; } return itude; } /** * 獲取地理位置 * * @throws Exception */ private String getLocation(SItude itude) throws Exception { String resultString = ""; /** 這裡采用get方法,直接將參數加到URL上 */ String urlString = String.format("https://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s", itude.latitude, itude.longitude); Log.i("URL", urlString); /** 新建HttpClient */ HttpClient client = new DefaultHttpClient(); /** 采用GET方法 */ HttpGet get = new HttpGet(urlString); try { /** 發起GET請求並獲得返回數據 */ HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer strBuff = new StringBuffer(); String result = null; while ((result = buffReader.readLine()) != null) { strBuff.append(result); } resultString = strBuff.toString(); /** 解析JSON數據,獲得物理地址 */ if (resultString != null && resultString.length() > 0) { JSONObject jsonobject = new JSONObject(resultString); JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString()); resultString = ""; for (int i = 0; i < jsonArray.length(); i++) { resultString = jsonArray.getJSONObject(i).getString("address"); } } } catch (Exception e) { throw new Exception("獲取物理位置出現錯誤:" + e.getMessage()); } finally { get.abort(); client = null; } return resultString; } /** 顯示結果 */ private void showResult(SCell cell, String location) { TextView cellText = (TextView) findViewById(R.id.cellText); cellText.setText(String.format("基站信息:mcc:%d, mnc:%d, lac:%d, cid:%d", cell.MCC, cell.MNC, cell.LAC, cell.CID)); TextView locationText = (TextView) findViewById(R.id.lacationText); locationText.setText("物理位置:" + location); }
把手機連上,跑起來看看。順利的話程式會自動跳到主介面,點擊「Click Me」,結果出錯了!

錯誤訊息是:Neither user 10078 nor current process has android.permission.ACCESS_COARSE_LOCATION. 原來是缺權限。前面學過,Android 在安全設計上頗下功夫,用到特殊功能得先聲明,安裝時列出來給使用者看,並取得同意。我們用到取得基站資訊的功能,涉及使用者隱私,所以必須先聲明。
打開 AndroidManifest.xml,加入相應的權限設定:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
順便把網路連線的權限也一起加上:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
再編譯運行看看(點擊「Click Me」後程式會短暫卡住,等一段時間才有反應,取決於網路狀況):

成功囉!
如果你還是遇到錯誤,可以對照以下幾種常見情況排查:
█ 出現「www.google.com…」之類的錯誤:請確認手機能連上網,呼叫 Google API 一定要聯網。
█ 取不到基站資訊:確認你是在真機上測試的嗎?模擬器可不行。另外這個範例只支援 GSM 網路,若手機用的是 CDMA 就無法運作。
█ 取不到經緯度:很可能你所在的基站還沒被 Google 收錄,之前我也遇過怎麼查都查不到、回傳為空的情況。
█ 取得的地址不正確:可能是程式邏輯出了問題,也可能是 Google 那邊的資料有誤。
其實 Google Map API 回傳的資料還包含很多其他資訊,我們可以用來開發更有趣的功能,例如自製地圖、足跡記錄等等,就看你如何發揮創意了。
這個程式大致實現了基站定位,但仍有不少待改進之處:點擊按鈕後介面會卡住(因為訪問網路時阻塞了執行緒)、異常處理不夠完善、不支援 CDMA 網路等。
此外精度也有限,取到的其實是基站的實體位置,跟使用者所在位置仍有落差。城市裡多採用密集的小功率基站,精度約在幾百公尺內;郊區則多為大功率基站、密度低,精度往往在幾公里以上。若要更高精度,得靠額外的演算法來補強,有興趣的朋友我們日後再單獨寫一篇來研究。
由此可見,寫一段程式和做一個真正的產品之間,還有很大一段距離。
這一篇基本上實現了最簡單的基站定位,僅供學習參考,離產品級要求還遠。我們也順帶複習了 Java 編碼,之前 Java 基礎較薄弱、讀起來有點吃力的朋友,建議找本 Java 入門書補強一下。以上是本文全部內容,希望對大家的學習有所幫助。