android 三种定位方式

Android定位技术详解
本文详细介绍Android平台上的三种定位技术:GPS定位、基站定位和网络定位。通过具体代码示例展示了如何实现这些定位功能,并解释了相关权限配置。

最近在看android关于定位的方式,查了很多资料,也做了相关实验,在手机上做了测试,下面总结:

一共有三种定位方式,一种是GPS,一种是通过网络的方式,一种则是在基于基站的方式,但是,不管哪种方式,都需要开启网络或者GPS

首先添加权限

[html] view plain copy
  1. <uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
  2. <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>

在COARSE_LOCATION是用于基站定位的时候用的,没有这个权限,在获取getCellLocation的时候报错。

第一种方式通过JASON来实现,是通过基站方式的,引用文章地址:http://www.cnblogs.com/dartagnan/archive/2011/3/9.html,下载只是实现定位的代码

[java] view plain copy
  1. /**
  2. *Google定位的实现.<br/>
  3. *Geolocation的详细信息请参见:<br/>
  4. *<a
  5. *href="http://code.google.com/apis/gears/geolocation_network_protocol.html"mce_href="http://code.google.com/apis/gears/geolocation_network_protocol.html">
  6. *http://code.google.com/apis/gears/geolocation_network_protocol.html</a>
  7. */
  8. publicclassLocationActextendsActivity{
  9. privateTextViewtxtInfo;
  10. publicvoidonCreate(BundlesavedInstanceState){
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.main);
  13. Buttonbtn=(Button)findViewById(R.id.btnStart);
  14. txtInfo=(TextView)findViewById(R.id.txtInfo);
  15. btn.setOnClickListener(newButton.OnClickListener(){
  16. publicvoidonClick(Viewview){
  17. getLocation();
  18. }
  19. });
  20. }
  21. privatevoidgetLocation(){
  22. TelephonyManagertm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  23. GsmCellLocationgsmCell=(GsmCellLocation)tm.getCellLocation();
  24. intcid=gsmCell.getCid();
  25. intlac=gsmCell.getLac();
  26. StringnetOperator=tm.getNetworkOperator();
  27. intmcc=Integer.valueOf(netOperator.substring(0,3));
  28. intmnc=Integer.valueOf(netOperator.substring(3,5));
  29. JSONObjectholder=newJSONObject();
  30. JSONArrayarray=newJSONArray();
  31. JSONObjectdata=newJSONObject();
  32. try{
  33. holder.put("version","1.1.0");
  34. holder.put("host","maps.google.com");
  35. holder.put("address_language","zh_CN");
  36. holder.put("request_address",true);
  37. holder.put("radio_type","gsm");
  38. holder.put("carrier","HTC");
  39. data.put("cell_id",cid);
  40. data.put("location_area_code",lac);
  41. data.put("mobile_countyr_code",mcc);
  42. data.put("mobile_network_code",mnc);
  43. array.put(data);
  44. holder.put("cell_towers",array);
  45. }catch(JSONExceptione){
  46. e.printStackTrace();
  47. }
  48. DefaultHttpClientclient=newDefaultHttpClient();
  49. HttpPosthttpPost=newHttpPost("http://www.google.com/loc/json");
  50. StringEntitystringEntity=null;
  51. try{
  52. stringEntity=newStringEntity(holder.toString());
  53. }catch(UnsupportedEncodingExceptione){
  54. e.printStackTrace();
  55. }
  56. httpPost.setEntity(stringEntity);
  57. HttpResponsehttpResponse=null;
  58. try{
  59. httpResponse=client.execute(httpPost);
  60. }catch(ClientProtocolExceptione){
  61. e.printStackTrace();
  62. }catch(IOExceptione){
  63. e.printStackTrace();
  64. }
  65. HttpEntityhttpEntity=httpResponse.getEntity();
  66. InputStreamis=null;
  67. try{
  68. is=httpEntity.getContent();
  69. }catch(IllegalStateExceptione){
  70. e.printStackTrace();
  71. }catch(IOExceptione){
  72. //TODOAuto-generatedcatchblock
  73. e.printStackTrace();
  74. }
  75. InputStreamReaderisr=newInputStreamReader(is);
  76. BufferedReaderreader=newBufferedReader(isr);
  77. StringBufferstringBuffer=newStringBuffer();
  78. try{
  79. Stringresult="";
  80. while((result=reader.readLine())!=null){
  81. stringBuffer.append(result);
  82. }
  83. }catch(IOExceptione){
  84. e.printStackTrace();
  85. }
  86. txtInfo.setText(stringBuffer.toString());
  87. }
  88. }

第二种通过严格的GPS来定位,引用文章地址: http://www.cnblogs.com/wisekingokok/archive/2011/09/06/2168479.html ,这里只引用代码

[java] view plain copy
  1. publicclassMainActivityextendsActivity{
  2. privateLocationManagerlocationManager;
  3. privateGpsStatusgpsstatus;
  4. @Override
  5. publicvoidonCreate(BundlesavedInstanceState){
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.main);
  8. //获取到LocationManager对象
  9. locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
  10. //根据设置的Criteria对象,获取最符合此标准的provider对象
  11. StringcurrentProvider=locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
  12. //根据当前provider对象获取最后一次位置信息
  13. LocationcurrentLocation=locationManager.getLastKnownLocation(currentProvider);
  14. //如果位置信息为null,则请求更新位置信息
  15. if(currentLocation==null){
  16. locationManager.requestLocationUpdates(currentProvider,0,0,locationListener);
  17. }
  18. //增加GPS状态监听器
  19. locationManager.addGpsStatusListener(gpsListener);
  20. //直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度
  21. //每隔10秒获取一次位置信息
  22. while(true){
  23. currentLocation=locationManager.getLastKnownLocation(currentProvider);
  24. if(currentLocation!=null){
  25. Log.d("Location","Latitude:"+currentLocation.getLatitude());
  26. Log.d("Location","location:"+currentLocation.getLongitude());
  27. break;
  28. }else{
  29. Log.d("Location","Latitude:"+0);
  30. Log.d("Location","location:"+0);
  31. }
  32. try{
  33. Thread.sleep(10000);
  34. }catch(InterruptedExceptione){
  35. Log.e("Location",e.getMessage());
  36. }
  37. }
  38. }
  39. privateGpsStatus.ListenergpsListener=newGpsStatus.Listener(){
  40. //GPS状态发生变化时触发
  41. @Override
  42. publicvoidonGpsStatusChanged(intevent){
  43. //获取当前状态
  44. gpsstatus=locationManager.getGpsStatus(null);
  45. switch(event){
  46. //第一次定位时的事件
  47. caseGpsStatus.GPS_EVENT_FIRST_FIX:
  48. break;
  49. //开始定位的事件
  50. caseGpsStatus.GPS_EVENT_STARTED:
  51. break;
  52. //发送GPS卫星状态事件
  53. caseGpsStatus.GPS_EVENT_SATELLITE_STATUS:
  54. Toast.makeText(MainActivity.this,"GPS_EVENT_SATELLITE_STATUS",Toast.LENGTH_SHORT).show();
  55. Iterable<GpsSatellite>allSatellites=gpsstatus.getSatellites();
  56. Iterator<GpsSatellite>it=allSatellites.iterator();
  57. intcount=0;
  58. while(it.hasNext())
  59. {
  60. count++;
  61. }
  62. Toast.makeText(MainActivity.this,"SatelliteCount:"+count,Toast.LENGTH_SHORT).show();
  63. break;
  64. //停止定位事件
  65. caseGpsStatus.GPS_EVENT_STOPPED:
  66. Log.d("Location","GPS_EVENT_STOPPED");
  67. break;
  68. }
  69. }
  70. };
  71. //创建位置监听器
  72. privateLocationListenerlocationListener=newLocationListener(){
  73. //位置发生改变时调用
  74. @Override
  75. publicvoidonLocationChanged(Locationlocation){
  76. Log.d("Location","onLocationChanged");
  77. }
  78. //provider失效时调用
  79. @Override
  80. publicvoidonProviderDisabled(Stringprovider){
  81. Log.d("Location","onProviderDisabled");
  82. }
  83. //provider启用时调用
  84. @Override
  85. publicvoidonProviderEnabled(Stringprovider){
  86. Log.d("Location","onProviderEnabled");
  87. }
  88. //状态改变时调用
  89. @Override
  90. publicvoidonStatusChanged(Stringprovider,intstatus,Bundleextras){
  91. Log.d("Location","onStatusChanged");
  92. }
  93. };
  94. }

第三种主要是通过网络的方式来定位,引用文章地址: http://www.cnblogs.com/wisekingokok/archive/2011/09/05/2167755.html ,这里只写代码

[java] view plain copy
  1. packagecom.test;
  2. importjava.io.IOException;
  3. importjava.util.List;
  4. importandroid.app.Activity;
  5. importandroid.location.Address;
  6. importandroid.location.Criteria;
  7. importandroid.location.Geocoder;
  8. importandroid.location.Location;
  9. importandroid.location.LocationListener;
  10. importandroid.location.LocationManager;
  11. importandroid.os.Bundle;
  12. importandroid.util.Log;
  13. importandroid.widget.Toast;
  14. publicclassMainActivityextendsActivity{
  15. @Override
  16. publicvoidonCreate(BundlesavedInstanceState){
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.main);
  19. //获取到LocationManager对象
  20. LocationManagerlocationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
  21. //创建一个Criteria对象
  22. Criteriacriteria=newCriteria();
  23. //设置粗略精确度
  24. criteria.setAccuracy(Criteria.ACCURACY_COARSE);
  25. //设置是否需要返回海拔信息
  26. criteria.setAltitudeRequired(false);
  27. //设置是否需要返回方位信息
  28. criteria.setBearingRequired(false);
  29. //设置是否允许付费服务
  30. criteria.setCostAllowed(true);
  31. //设置电量消耗等级
  32. criteria.setPowerRequirement(Criteria.POWER_HIGH);
  33. //设置是否需要返回速度信息
  34. criteria.setSpeedRequired(false);
  35. //根据设置的Criteria对象,获取最符合此标准的provider对象
  36. StringcurrentProvider=locationManager.getBestProvider(criteria,true);
  37. Log.d("Location","currentProvider:"+currentProvider);
  38. //根据当前provider对象获取最后一次位置信息
  39. LocationcurrentLocation=locationManager.getLastKnownLocation(currentProvider);
  40. //如果位置信息为null,则请求更新位置信息
  41. if(currentLocation==null){
  42. locationManager.requestLocationUpdates(currentProvider,0,0,locationListener);
  43. }
  44. //直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度
  45. //每隔10秒获取一次位置信息
  46. while(true){
  47. currentLocation=locationManager.getLastKnownLocation(currentProvider);
  48. if(currentLocation!=null){
  49. Log.d("Location","Latitude:"+currentLocation.getLatitude());
  50. Log.d("Location","location:"+currentLocation.getLongitude());
  51. break;
  52. }else{
  53. Log.d("Location","Latitude:"+0);
  54. Log.d("Location","location:"+0);
  55. }
  56. try{
  57. Thread.sleep(10000);
  58. }catch(InterruptedExceptione){
  59. Log.e("Location",e.getMessage());
  60. }
  61. }
  62. //解析地址并显示
  63. GeocodergeoCoder=newGeocoder(this);
  64. try{
  65. intlatitude=(int)currentLocation.getLatitude();
  66. intlongitude=(int)currentLocation.getLongitude();
  67. List<Address>list=geoCoder.getFromLocation(latitude,longitude,2);
  68. for(inti=0;i<list.size();i++){
  69. Addressaddress=list.get(i);
  70. Toast.makeText(MainActivity.this,address.getCountryName()+address.getAdminArea()+address.getFeatureName(),Toast.LENGTH_LONG).show();
  71. }
  72. }catch(IOExceptione){
  73. Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
  74. }
  75. }
  76. //创建位置监听器
  77. privateLocationListenerlocationListener=newLocationListener(){
  78. //位置发生改变时调用
  79. @Override
  80. publicvoidonLocationChanged(Locationlocation){
  81. Log.d("Location","onLocationChanged");
  82. Log.d("Location","onLocationChangedLatitude"+location.getLatitude());
  83. Log.d("Location","onLocationChangedlocation"+location.getLongitude());
  84. }
  85. //provider失效时调用
  86. @Override
  87. publicvoidonProviderDisabled(Stringprovider){
  88. Log.d("Location","onProviderDisabled");
  89. }
  90. //provider启用时调用
  91. @Override
  92. publicvoidonProviderEnabled(Stringprovider){
  93. Log.d("Location","onProviderEnabled");
  94. }
  95. //状态改变时调用
  96. @Override
  97. publicvoidonStatusChanged(Stringprovider,intstatus,Bundleextras){
  98. Log.d("Location","onStatusChanged");
  99. }
  100. };
  101. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值