用戶帶和他們的移動設備與他們幾乎無處不在。移動應用程式的獨特功能之一是位置意識。明確的位置定位,並明智地使用資訊,可以讓消費者體驗帶來了更多的便利。
這篇文章將告訴你,如何在你的Android應用程式將基於位置的服務。您會學到一些方法,以接收位置更新和最佳做法。本文的重點分為下面三點,下面會一一講到,並指出其中的重點內容:
1.使用LocationManager(學習如何配置你的app,在它能接受到android的位置更新之前)
2.獲取當前位置(學習如何使用底層位置技術平臺上可用來獲得當前位置)
3.顯示位置位址(學習如何翻譯為位址位置坐標對用戶是可讀的)
一.使用LocationManager
在manifest中聲明網絡權限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
獲得位置管理的引用:
LocationManager是主要的類,通過這個應用程式可以訪問的位置服務在Android上。類似於其他系統服務,可以得到一個引用從調用getSystemService()方法。如果你的應用程式准備接收位置更新前景(在一個活動),您應該執行該步驟通常在onCreate()方法。代碼如下:
LocationManager locationManager =
(LocationManager) this.getSystemService(CoNtext.LOCATION_SERVICE);
獲得位置的提供者:
取決於您的應用程式的用例,你必須選擇一個特定位置,或多個提供者、提供者基於類似的權衡。例如,一個的興趣點簽入應用程式將需要更高的定位精度比說,零售商店定位器,一個城市水準位置修正就足夠了。下面的代碼片段要求一個提供者支援的GPS。代碼如下:
LocationProvider provider =
locationManager.getProvider(LocationManager.GPS_PROVIDER);
添加條件增加精確度:
你可以提供一些輸入標准如精度、電力需求,貨幣成本等等,讓Android決定一個最接近的匹配位置提供者。下面的代碼片段要求一個位置提供者與細准確性和沒有貨幣成本。注意,標准可能沒有解決任何提供者,在這種情況下,將返回null。代碼如下:
// Retrieve a list of location providers that have fine accuracy, no monetary cost, etc
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(false);
...
String providerName = locManager.getBestProvider(criteria, true);
// If no suitable provider is found, null is returned.
if (providerName != null) {
...
}
驗證位置提供者是否可以:
如果位置提供者是禁用的,您可以為用戶提供一個機會,使它在設置一個Intent的
ACTION_LOCATION_SOURCE_SETTINGS,代碼如下:
@Override
protected void onStart() {
super.onStart();
// This verification should be done during onStart() because the system calls
// this method when the user returns to the activity, which ensures the desired
// location provider is enabled each time the activity resumes from the stopped state.
LocationManager locationManager =
(LocationManager) getSystemService(CoNtext.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
// Build an alert dialog here that requests that the user enable
// the location services, then when the user clicks the "OK" button,
// call enableLocationSettings()
}
}
private void enableLocationSettings() {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
二.獲取當前位置
設置位置的監聽
LocationManager類公開的一些方法來應用程式接收位置更新。在其最簡單的形式,你注冊一個事件偵聽器,確定位置的經理,你想接收位置更新,並指定最小間隔時間和距離,接收位置更新。這個onLocationChanged()回調將調用的頻率與時間和距離的間隔。在樣例代碼片段,下面的位置偵聽器被設置為接收通知至少每10秒,如果設備移動超過10米。其他的回調方法通知應用程式狀態更改任何來自提供者的位置。代碼如下:
private final LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// A new location update is received. Do something useful with it. In this case,
// we're sending the update to a handler which then updates the UI with the new
// location.
Message.obtain(mHandler,
UPDATE_LATLNG,
location.getLatitude() + ", " +
location.getLongitude()).sendToTarget();
...
}
...
};
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, // 10-second interval.
10, // 10 meters.
listener);
停止位置更新:
如果用戶不再使用導航或者使用別的應用時,你應該停止位置更新通過調用removeUpdates()在onStop()。(onStop()時調用活動不再是可見的,代碼如下:
protected void onStop() {
super.onStop();
mLocationManager.removeUpdates(listener);
}
三.顯示位置位址
執行反向位址編碼:
逆向地理編碼是翻譯的過程,一個人類可讀的緯度經度坐標位址。注意,在幕後,API是依賴於web服務。如果這樣的服務不可用的設備,API將拋出一個「Service not Available exception」或者返回一個空清單的位址。
一個helper方法稱為isPresent()添加於Android 2.3(API級別9)來檢查服務的存在,
下面的代碼片段演示了如何使用該API來執行反向地理編碼Geocoder。代碼如下:
private final LocationListener listener = new LocationListener() {
public void onLocationChanged(Location location) {
// Bypass reverse-geocoding if the Geocoder service is not available on the
// device. The isPresent() convenient method is only available on Gingerbread or above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent()) {
// Since the geocoding API is synchronous and may take a while. You don't want to lock
// up the UI thread. Invoking reverse geocoding in an AsyncTask.
(new ReverseGeocodingTask(this)).execute(new Location[] {location});
}
}
...
};
// AsyncTask encapsulating the reverse-geocoding API. Since the geocoder API is blocked,
// we do not want to invoke it from the UI thread.
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
CoNtext mCoNtext;
public ReverseGeocodingTask(CoNtext coNtext) {
super();
mCoNtext = coNtext;
}
@Override
protected Void doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(mCoNtext, Locale.getDefault());
Location loc = params[0];
List<Address> addresses = null;
try {
// Call the synchronous getFromLocation() method by passing in the lat/long values.
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
// Update UI field with the exception.
Message.obtain(mHandler, UPDATE_ADDRESS, e.toString()).sendToTarget();
}
if (addresses != null &s;&s; addresses.size() > 0) {
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
// Update the UI via a message handler.
Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
}
return null;
}
}
以上就是詳細的對app定位的一些講解和事例代碼,只有部分代碼,為的是突出重點和幫助大家理解,下面我貼上該例子全部的源代碼,代碼也不多,注釋也很清楚,希望能幫到大家。
留言列表