編輯:關於 Android 程式設計
Android 上的定位大致可分成四種途徑:GPS、基站、WIFI 與 AGPS。它們各有擅場,也各有明顯的短板,實務上多半是組み合わせて用,才能兼顧精度、耗電與可用性。
GPS 直接與衛星通信取得經緯度,精度是四者之中最高的,現今的 Android 手機幾乎都具備 GPS 模組。但它的缺點同樣鮮明:
其中第 2、3 點最為致命。值得一提的是,GPS 走的是衛星通道,在沒有網路連線的情況下依然可用。
使用前需在 AndroidManifest.xml 加上權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
先檢查 GPS 模組是否存在並已開啟:
private void openGPSSettings() {
LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS模塊正常", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(this, "請開啟GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivityForResult(intent, 0); // 設定完成後返回
}
開啟正常就直接進入顯示頁,否則導向設定頁。取得位置的程式碼如下:
private void getLocation() {
// 取得位置管理服務
LocationManager locationManager;
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager) this.getSystemService(serviceName);
// 以 Criteria 描述我們想要什麼樣的定位來源
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
String provider = locationManager.getBestProvider(criteria, true);
// 先取最後已知位置,讓畫面有東西可顯示
Location location = locationManager.getLastKnownLocation(provider);
updateToNewLocation(location);
// 註冊監聽器:最小更新間隔 100 秒、最小位移 500 公尺
locationManager.requestLocationUpdates(provider, 100 * 1000, 500, locationListener);
}
private void updateToNewLocation(Location location) {
TextView tv1 = (TextView) this.findViewById(R.id.tv1);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
tv1.setText("維度:" + latitude + "\n經度:" + longitude);
} else {
tv1.setText("無法獲取地理信息");
}
}
基站定位的原理不難理解,一般有兩種做法。第一種是利用手機附近的三個基站做三角定位——基站位置固定,透過電磁波在三者之間中轉所需的時間差反推座標。第二種是取得最近基站的一組資訊(基站 id、location area code、mobile country code、mobile network code 與訊號強度),送到定位服務比對資料庫,誤差通常在數十到數百公尺之間。
其中訊號強度特別關鍵。網路上許多號稱「手動用基站定位」的方法之所以誤差過大,多半就是漏掉了這個欄位。
WIFI 定位靠的是熱點的 BSSID(MAC 位址)對應的位置資料:只要偵測到熱點存在即可,不需要真正連上。由於基站與 WIFI 都需要網路,Android 把兩者合稱為 Network provider。
取得 WIFI MAC 位址:
public class WiFiInfoManager implements Serializable {
private static final long serialVersionUID = -4582739827003032383L;
private Context context;
public WiFiInfoManager(Context context) {
super();
this.context = context;
}
public WifiInfo getWifiInfo() {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = new WifiInfo();
info.mac = manager.getConnectionInfo().getBSSID();
Log.i(TAG, "WIFI MAC is: " + info.mac);
return info;
}
public class WifiInfo {
public String mac;
}
}
把 BSSID 與訊號強度送到定位服務換取座標:
public static Location getWIFILocation(WifiInfo wifi) {
if (wifi == null) {
Log.i(TAG, "wifi is null.");
return null;
}
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/loc/json");
JSONObject holder = new JSONObject();
try {
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
JSONArray array = new JSONArray();
if (wifi.mac != null && wifi.mac.trim().length() > 0) {
JSONObject data = new JSONObject();
data.put("mac_address", wifi.mac);
data.put("signal_strength", 8); // 訊號強度不可省略
data.put("age", 0);
array.put(data);
}
holder.put("wifi_towers", array);
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
HttpResponse resp = client.execute(post);
int state = resp.getStatusLine().getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity entity = resp.getEntity();
if (entity != null) {
BufferedReader br = new BufferedReader(
new InputStreamReader(entity.getContent()));
StringBuffer sb = new StringBuffer();
String resute = "";
while ((resute = br.readLine()) != null) {
sb.append(resute);
}
br.close();
JSONObject data = new JSONObject(sb.toString());
data = (JSONObject) data.get("location");
Location loc = new Location(
android.location.LocationManager.NETWORK_PROVIDER);
loc.setLatitude((Double) data.get("latitude"));
loc.setLongitude((Double) data.get("longitude"));
loc.setAccuracy(Float.parseFloat(data.get("accuracy").toString()));
loc.setTime(System.currentTimeMillis());
return loc;
}
}
return null;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return null;
}
}
AGPS(Assisted GPS,輔助全球衛星定位系統)結合了 GSM/GPRS 網路與傳統衛星定位:由基地台代為傳送輔助星曆等資訊,縮短 GPS 晶片搜尋衛星的時間;在遮蔽嚴重的室內,也能靠基地台訊號彌補,降低對衛星的依賴。
相較於純 GPS 與基地台三角定位,AGPS 在廣度、耗電與速度上都有更好的平衡,理想誤差可壓在 10 公尺以內。日本與美國都已將 AGPS 成熟應用於 LBS(Location Based Service,基於位置的服務)。
技術上,AGPS 需要在手機內加裝 GPS 接收機模組、改有天線,並在行動網路側建置位置服務器與差分 GPS 基準站。它的優勢主要在精度:在室外空曠處可達 10 公尺左右,堪稱目前精度最高的定位技術之一;另一個優點是首次捕獲時間通常只需數秒,不像純 GPS 可能要等上 2 到 3 分鐘。
實際的 App 幾乎不會只依賴單一方式。常見策略是先用 getLastKnownLocation() 快速填滿畫面,再向 NETWORK_PROVIDER 索取一個粗略位置,同時在背景請求 GPS 做精細定位,並依精度需求與電量狀況動態調整更新頻率。Google Play 服務的 FusedLocationProviderClient 正是把這套取捨邏輯封裝起來的官方方案,並額外提供「目前是否有人在使用」的脈衝式更新,值得優先採用。
另外提醒:Android 6.0 之後 ACCESS_FINE_LOCATION 屬於執行期權限,需在執行時動態請求;ACCESS_COARSE_LOCATION 則對應基站與 WIFI 這類粗定位;而 DefaultHttpClient 與 Google 的 loc/json 端點都已是歷史產物,新專案請改用 HttpURLConnection 或 OkHttp,並以現行合法的地圖/定位服務取代。
Android 學習之路:從非 Java 工程師視角理解系統架構與專案結構
從非 Java 工程師的視角開始 這是「Android 學習之路」系列的第一篇。本文先不急著實作簡易版微信,而是把學習起點、對 Android 的理解,以及 Androi
Android 實戰:從相冊或拍照裁剪圖片並設置頭像
使用過 QQ、微信等聊天工具的讀者對設置頭像的流程一定不陌生:從本地相冊選擇圖片或用手機拍照,然後裁剪出喜歡的部分作為頭像。本文將完整實現這一流程,並額外加入把裁剪後的圖
Android 網路編程之 Socket 通信總結
建立伺服器端的步驟: 1. 指定埠號,實例化一個 ServerSocket。 2. 呼叫 ServerSocket 的 accept 方法,等待連線期間會阻塞。 3. 取
Android 屬性動畫完整指南:ObjectAnimator、ValueAnimator 與 AnimatorSet
Android 的 Property Animation 以改變物件屬性為核心,適合處理顏色、3D 旋轉、位移與透明度等更複雜的動畫需求。 核心概念 Duration: