編輯:關於 Android 程式設計
Android 之所以在行動應用上特別強大,很大一部分來自它對硬體能力的封裝。定位就是最典型的一項:你只要透過系統服務 LocationManager,就能拿到裝置目前所在的經緯度與海拔,而不必去操心底層是走 GPS 晶片還是基站三角定位。
所有定位相關的操作都從系統服務開始,用 getSystemService 拿到 LocationManager,接著註冊位置更新,最後讀取一次「最後已知位置」作為初始值。
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
// 每 10000 毫秒更新一次,且忽略 0 公尺以內的位移
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10000, 0, locationListener);
Location location = locationManager.getLastKnownLocation(
LocationManager.GPS_PROVIDER);
String latitude = Double.toString(location.getLatitude());
String longitude = Double.toString(location.getLongitude());
String altitude = Double.toString(location.getAltitude());
TextView tv = (TextView) findViewById(R.id.local);
tv.setText("latitude:" + latitude + " longitude:" + longitude
+ " altitude:" + altitude);
requestLocationUpdates 的第二、三個參數分別是「最小時間間隔」與「最小位移間隔」,最後一個參數則是接收回呼的 LocationListener。把時間間隔調小會讓定位更即時,但也更耗電,實務上需要權衡。
private final LocationListener locationListener = new LocationListener() {
// 座標改變時觸發;若 Provider 回報的是同一組座標則不會觸發
public void onLocationChanged(Location location) {
if (location != null) {
String latitude = Double.toString(location.getLatitude());
String longitude = Double.toString(location.getLongitude());
String altitude = Double.toString(location.getAltitude());
TextView tv = (TextView) findViewById(R.id.local);
tv.setText("latitude:" + latitude + " longitude:"
+ longitude + " altitude:" + altitude);
}
}
// Provider 被關閉時觸發,例如使用者關掉 GPS
public void onProviderDisabled(String provider) { }
// Provider 被開啟時觸發,例如使用者打開 GPS
public void onProviderEnabled(String provider) { }
// Provider 狀態在「可用 / 暫時不可用 / 無服務」之間切換時觸發
public void onStatusChanged(String provider, int status, Bundle extras) { }
};
別忘了在 AndroidManifest.xml 加上定位權限,否則執行期會直接拿到空值或丟出安全性例外:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
沒有實機時,可以用 ADT 提供的 Emulator Control 檢視(Window → Show View 中開啟)手動送一組座標,或載入 KML/GPX 檔案回放一段軌跡。
另一條路是走 telnet:先開命令列執行 telnet 5554,進入後輸入:
geo fix -39.4 116.9 326
三個參數依序是經度、緯度、海拔,其中海拔可以省略。送出後,App 端就會收到一次位置更新,整個定位流程於是可以在沒有 GPS 模組的開發環境裡完整跑通。
React Native Android 篇:Touch 事件源碼原理與五種按壓狀態效果實作
Native 相比 Hybrid 或 H5 最大的優勢,就在於流暢且複雜的互動效果,觸摸事件正是其中的核心,包含點擊(Click)、長按(LongClick)與手勢(Ge
Android 四大元件之 Service 篇
以前我總覺得四大元件裡的 Service 和 BroadcastReceiver 用得少,其實不然,只是因為它們比較抽象,總是默默無聞地在後台提供服務。 我寫了個 dem
Android Notification 通知機制完整詳解
Notification 簡介 Notification 是顯示在手機狀態列的通知,代表一種具有全域效果的通知訊息,程式通常透過 NotificationManager
Android Studio 中的 AIDL 跨進程服務入門
為什麼需要 AIDL AIDL 常用於不同應用程式之間的跨進程通訊。若只是單向通知,Messenger 已足夠;但若需要多客戶端併發存取,並自行處理執行緒安全,AIDL