2011年4月11日 星期一

Location acquisition on Android

Location / Context Aware Computing 自90年代開始被廣泛的討論與研究
在 Android 的平台中 , google 提供了兩種獲取 location 資訊的管道
第一個是大家平常較為熟知的 GPS , 然而這裡要分享的則是透過 Wifi 的
Network Location Provider

動作摘要
1. 取得 LocationManager 的 instance
2. 撰寫聽取相關事件的 Listener
3. 註冊事件

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}

public void onStatusChanged(String provider, int status, Bundle extras) {}

public void onProviderEnabled(String provider) {}

public void onProviderDisabled(String provider) {}
};

// Register the listener with the Location Manager to receive location updates ,
// 第2,3個參數用來控制update的頻率
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

另外必須獲取權限如下:
  1. <manifest ... >
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    ...
    manifest>


沒有留言:

張貼留言