用户带和他们的移动设备与他们几乎无处不在。移动应用程序的独特功能之一是位置意识。明确的位置定位,并明智地使用信息,可以让使用者体验带来了更多的便利。
这篇文章将告诉你,如何在你的Android应用程序将基于位置的服务。您会学到一些方法,以接收位置更新和最佳做法。本文的重点分为下面三点,下面会一一讲到,并指出其中的重点内容:
1.使用LocationManager(学习如何配置你的app,在它能接受到android的位置更新之前)
2.获取当前位置(学习如何使用底层位置技术平台上可用来获得当前位置)
3.显示位置地址(学习如何翻译为地址位置坐标对用户是可读的)
一.使用LocationManager
在manifest中声明网络权限:
- <uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permissionandroid:name="android.permission.INTERNET"/>
获得位置管理的引用:
LocationManager是主要的类,通过这个应用程序可以访问的位置服务在Android上。类似于其他系统服务,可以得到一个引用从调用getSystemService()方法。如果你的应用程序准备接收位置更新前景(在一个活动),您应该执行该步骤通常在onCreate()方法。代码如下:
- LocationManagerlocationManager=
- (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
获得位置的提供者:
取决于您的应用程序的用例,你必须选择一个特定位置,或多个提供者、提供者基于类似的权衡。例如,一个的兴趣点签入应用程序将需要更高的定位精度比说,零售商店定位器,一个城市水平位置修正就足够了。下面的代码片段要求一个提供者支持的GPS。代码如下:
- LocationProviderprovider=
- locationManager.getProvider(LocationManager.GPS_PROVIDER);
添加条件增加精确度:
你可以提供一些输入标准如精度、电力需求,货币成本等等,让Android决定一个最接近的匹配位置提供者。下面的代码片段要求一个位置提供者与细准确性和没有货币成本。注意,标准可能没有解决任何提供者,在这种情况下,将返回null。代码如下:
- //Retrievealistoflocationprovidersthathavefineaccuracy,nomonetarycost,etc
- Criteriacriteria=newCriteria();
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- criteria.setCostAllowed(false);
- ...
- StringproviderName=locManager.getBestProvider(criteria,true);
- //Ifnosuitableproviderisfound,nullisreturned.
- if(providerName!=null){
- ...
- }
验证位置提供者是否可以:
如果位置提供者是禁用的,您可以为用户提供一个机会,使它在设置一个Intent的
ACTION_LOCATION_SOURCE_SETTINGS,代码如下:
- @Override
- protectedvoidonStart(){
- super.onStart();
- //ThisverificationshouldbedoneduringonStart()becausethesystemcalls
- //thismethodwhentheuserreturnstotheactivity,whichensuresthedesired
- //locationproviderisenabledeachtimetheactivityresumesfromthestoppedstate.
- LocationManagerlocationManager=
- (LocationManager)getSystemService(Context.LOCATION_SERVICE);
- finalbooleangpsEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
- if(!gpsEnabled){
- //Buildanalertdialogherethatrequeststhattheuserenable
- //thelocationservices,thenwhentheuserclicksthe"OK"button,
- //callenableLocationSettings()
- }
- }
- privatevoidenableLocationSettings(){
- IntentsettingsIntent=newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
- startActivity(settingsIntent);
- }
二.获取当前位置
设置位置的监听
LocationManager类公开的一些方法来应用程序接收位置更新。在其最简单的形式,你注册一个事件侦听器,确定位置的经理,你想接收位置更新,并指定最小间隔时间和距离,接收位置更新。这个onLocationChanged()回调将调用的频率与时间和距离的间隔。在样例代码片段,下面的位置侦听器被设置为接收通知至少每10秒,如果设备移动超过10米。其他的回调方法通知应用程序状态更改任何来自提供者的位置。代码如下:
- privatefinalLocationListenerlistener=newLocationListener(){
- @Override
- publicvoidonLocationChanged(Locationlocation){
- //Anewlocationupdateisreceived.Dosomethingusefulwithit.Inthiscase,
- //we'resendingtheupdatetoahandlerwhichthenupdatestheUIwiththenew
- //location.
- Message.obtain(mHandler,
- UPDATE_LATLNG,
- location.getLatitude()+","+
- location.getLongitude()).sendToTarget();
- ...
- }
- ...
- };
- mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
- 10000,//10-secondinterval.
- 10,//10meters.
- listener);
停止位置更新:
如果用户不再使用导航或者使用别的应用时,你应该停止位置更新通过调用removeUpdates()在onStop()。(onStop()时调用活动不再是可见的,代码如下:
- protectedvoidonStop(){
- super.onStop();
- mLocationManager.removeUpdates(listener);
- }
三.显示位置地址
执行反向地址编码:
逆向地理编码是翻译的过程,一个人类可读的纬度经度坐标地址。注意,在幕后,API是依赖于web服务。如果这样的服务不可用的设备,API将抛出一个“Service not Available exception”或者返回一个空列表的地址。
一个helper方法称为isPresent()添加于Android 2.3(API级别9)来检查服务的存在,
下面的代码片段演示了如何使用该API来执行反向地理编码Geocoder。代码如下:
- privatefinalLocationListenerlistener=newLocationListener(){
- publicvoidonLocationChanged(Locationlocation){
- //Bypassreverse-geocodingiftheGeocoderserviceisnotavailableonthe
- //device.TheisPresent()convenientmethodisonlyavailableonGingerbreadorabove.
- if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD&&Geocoder.isPresent()){
- //SincethegeocodingAPIissynchronousandmaytakeawhile.Youdon'twanttolock
- //uptheUIthread.InvokingreversegeocodinginanAsyncTask.
- (newReverseGeocodingTask(this)).execute(newLocation[]{location});
- }
- }
- ...
- };
- //AsyncTaskencapsulatingthereverse-geocodingAPI.SincethegeocoderAPIisblocked,
- //wedonotwanttoinvokeitfromtheUIthread.
- privateclassReverseGeocodingTaskextendsAsyncTask<Location,Void,Void>{
- ContextmContext;
- publicReverseGeocodingTask(Contextcontext){
- super();
- mContext=context;
- }
- @Override
- protectedVoiddoInBackground(Location...params){
- Geocodergeocoder=newGeocoder(mContext,Locale.getDefault());
- Locationloc=params[0];
- List<Address>addresses=null;
- try{
- //CallthesynchronousgetFromLocation()methodbypassinginthelat/longvalues.
- addresses=geocoder.getFromLocation(loc.getLatitude(),loc.getLongitude(),1);
- }catch(IOExceptione){
- e.printStackTrace();
- //UpdateUIfieldwiththeexception.
- Message.obtain(mHandler,UPDATE_ADDRESS,e.toString()).sendToTarget();
- }
- if(addresses!=null&s;&s;addresses.size()>0){
- Addressaddress=addresses.get(0);
- //Formatthefirstlineofaddress(ifavailable),city,andcountryname.
- StringaddressText=String.format("%s,%s,%s",
- address.getMaxAddressLineIndex()>0?address.getAddressLine(0):"",
- address.getLocality(),
- address.getCountryName());
- //UpdatetheUIviaamessagehandler.
- Message.obtain(mHandler,UPDATE_ADDRESS,addressText).sendToTarget();
- }
- returnnull;
- }
- }
以上就是详细的对app定位的一些讲解和事例代码,只有部分代码,为的是突出重点和帮助大家理解,下面我贴上该例子全部的源代码,代码也不多,注释也很清楚,希望能帮到大家。点击打开链接