`

让android的app可以定位

 
阅读更多

用户带和他们的移动设备与他们几乎无处不在。移动应用程序的独特功能之一是位置意识。明确的位置定位,并明智地使用信息,可以让使用者体验带来了更多的便利。

这篇文章将告诉你,如何在你的Andr​​oid应用程序将基于位置的服务。您会学到一些方法,以接收位置更新和最佳做法。本文的重点分为下面三点,下面会一一讲到,并指出其中的重点内容:

1.使用LocationManager(学习如何配置你的app,在它能接受到android的位置更新之前)

2.获取当前位置(学习如何使用底层位置技术平台上可用来获得当前位置)

3.显示位置地址(学习如何翻译为地址位置坐标对用户是可读的)

.使用LocationManager

manifest中声明网络权限:

Xml代码
  1. <uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
  2. <uses-permissionandroid:name="android.permission.INTERNET"/>

获得位置管理的引用:

LocationManager是主要的类,通过这个应用程序可以访问的位置服务在Android上。类似于其他系统服务,可以得到一个引用从调用getSystemService()方法。如果你的应用程序准备接收位置更新前景(在一个活动),您应该执行该步骤通常在onCreate()方法。代码如下:

Java代码
  1. LocationManagerlocationManager=
  2. (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

获得位置的提供者:

取决于您的应用程序的用例,你必须选择一个特定位置,或多个提供者、提供者基于类似的权衡。例如,一个的兴趣点签入应用程序将需要更高的定位精度比说,零售商店定位器,一个城市水平位置修正就足够了。下面的代码片段要求一个提供者支持的GPS。代码如下:

Java代码
  1. LocationProviderprovider=
  2. locationManager.getProvider(LocationManager.GPS_PROVIDER);

添加条件增加精确度:

你可以提供一些输入标准如精度、电力需求,货币成本等等,让Android决定一个最接近的匹配位置提供者。下面的代码片段要求一个位置提供者与细准确性和没有货币成本。注意,标准可能没有解决任何提供者,在这种情况下,将返回null。代码如下:

Java代码
  1. //Retrievealistoflocationprovidersthathavefineaccuracy,nomonetarycost,etc
  2. Criteriacriteria=newCriteria();
  3. criteria.setAccuracy(Criteria.ACCURACY_FINE);
  4. criteria.setCostAllowed(false);
  5. ...
  6. StringproviderName=locManager.getBestProvider(criteria,true);
  7. //Ifnosuitableproviderisfound,nullisreturned.
  8. if(providerName!=null){
  9. ...
  10. }

验证位置提供者是否可以:

如果位置提供者是禁用的,您可以为用户提供一个机会,使它在设置一个Intent的

ACTION_LOCATION_SOURCE_SETTINGS代码如下:

Java代码
  1. @Override
  2. protectedvoidonStart(){
  3. super.onStart();
  4. //ThisverificationshouldbedoneduringonStart()becausethesystemcalls
  5. //thismethodwhentheuserreturnstotheactivity,whichensuresthedesired
  6. //locationproviderisenabledeachtimetheactivityresumesfromthestoppedstate.
  7. LocationManagerlocationManager=
  8. (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  9. finalbooleangpsEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
  10. if(!gpsEnabled){
  11. //Buildanalertdialogherethatrequeststhattheuserenable
  12. //thelocationservices,thenwhentheuserclicksthe"OK"button,
  13. //callenableLocationSettings()
  14. }
  15. }
  16. privatevoidenableLocationSettings(){
  17. IntentsettingsIntent=newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  18. startActivity(settingsIntent);
  19. }

.获取当前位置

设置位置的监听

LocationManager类公开的一些方法来应用程序接收位置更新。在其最简单的形式,你注册一个事件侦听器,确定位置的经理,你想接收位置更新,并指定最小间隔时间和距离,接收位置更新。这个onLocationChanged()回调将调用的频率与时间和距离的间隔。在样例代码片段,下面的位置侦听器被设置为接收通知至少每10秒,如果设备移动超过10米。其他的回调方法通知应用程序状态更改任何来自提供者的位置。代码如下:

Java代码
  1. privatefinalLocationListenerlistener=newLocationListener(){
  2. @Override
  3. publicvoidonLocationChanged(Locationlocation){
  4. //Anewlocationupdateisreceived.Dosomethingusefulwithit.Inthiscase,
  5. //we'resendingtheupdatetoahandlerwhichthenupdatestheUIwiththenew
  6. //location.
  7. Message.obtain(mHandler,
  8. UPDATE_LATLNG,
  9. location.getLatitude()+","+
  10. location.getLongitude()).sendToTarget();
  11. ...
  12. }
  13. ...
  14. };
  15. mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
  16. 10000,//10-secondinterval.
  17. 10,//10meters.
  18. listener);

停止位置更新:

如果用户不再使用导航或者使用别的应用时,你应该停止位置更新通过调用removeUpdates()在onStop()。(onStop()时调用活动不再是可见的,代码如下:

Java代码
  1. protectedvoidonStop(){
  2. super.onStop();
  3. mLocationManager.removeUpdates(listener);
  4. }

.显示位置地址

执行反向地址编码:

逆向地理编码是翻译的过程,一个人类可读的纬度经度坐标地址。注意,在幕后,API是依赖于web服务。如果这样的服务不可用的设备,API将抛出一个“Service not Available exception”或者返回一个空列表的地址。

一个helper方法称为isPresent()添加于Android 2.3(API级别9)来检查服务的存在,

下面的代码片段演示了如何使用该API来执行反向地理编码Geocoder。代码如下:

Java代码
  1. privatefinalLocationListenerlistener=newLocationListener(){
  2. publicvoidonLocationChanged(Locationlocation){
  3. //Bypassreverse-geocodingiftheGeocoderserviceisnotavailableonthe
  4. //device.TheisPresent()convenientmethodisonlyavailableonGingerbreadorabove.
  5. if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD&&Geocoder.isPresent()){
  6. //SincethegeocodingAPIissynchronousandmaytakeawhile.Youdon'twanttolock
  7. //uptheUIthread.InvokingreversegeocodinginanAsyncTask.
  8. (newReverseGeocodingTask(this)).execute(newLocation[]{location});
  9. }
  10. }
  11. ...
  12. };
  13. //AsyncTaskencapsulatingthereverse-geocodingAPI.SincethegeocoderAPIisblocked,
  14. //wedonotwanttoinvokeitfromtheUIthread.
  15. privateclassReverseGeocodingTaskextendsAsyncTask<Location,Void,Void>{
  16. ContextmContext;
  17. publicReverseGeocodingTask(Contextcontext){
  18. super();
  19. mContext=context;
  20. }
  21. @Override
  22. protectedVoiddoInBackground(Location...params){
  23. Geocodergeocoder=newGeocoder(mContext,Locale.getDefault());
  24. Locationloc=params[0];
  25. List<Address>addresses=null;
  26. try{
  27. //CallthesynchronousgetFromLocation()methodbypassinginthelat/longvalues.
  28. addresses=geocoder.getFromLocation(loc.getLatitude(),loc.getLongitude(),1);
  29. }catch(IOExceptione){
  30. e.printStackTrace();
  31. //UpdateUIfieldwiththeexception.
  32. Message.obtain(mHandler,UPDATE_ADDRESS,e.toString()).sendToTarget();
  33. }
  34. if(addresses!=null&s;&s;addresses.size()>0){
  35. Addressaddress=addresses.get(0);
  36. //Formatthefirstlineofaddress(ifavailable),city,andcountryname.
  37. StringaddressText=String.format("%s,%s,%s",
  38. address.getMaxAddressLineIndex()>0?address.getAddressLine(0):"",
  39. address.getLocality(),
  40. address.getCountryName());
  41. //UpdatetheUIviaamessagehandler.
  42. Message.obtain(mHandler,UPDATE_ADDRESS,addressText).sendToTarget();
  43. }
  44. returnnull;
  45. }
  46. }

以上就是详细的对app定位的一些讲解和事例代码,只有部分代码,为的是突出重点和帮助大家理解,下面我贴上该例子全部的源代码,代码也不多,注释也很清楚,希望能帮到大家。点击打开链接


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics