Chinaunix首页 | 论坛 | 博客
  • 博客访问: 424375
  • 博文数量: 205
  • 博客积分: 5630
  • 博客等级: 大校
  • 技术积分: 1945
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-06 20:28
文章分类

全部博文(205)

文章存档

2016年(1)

2015年(6)

2014年(9)

2013年(10)

2012年(53)

2011年(25)

2010年(87)

2009年(14)

分类: Android平台

2014-11-24 14:01:33

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

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

 

首先添加权限

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 

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

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

通过JASON来实现,是通过基站方式的

  1. /**
  2.   * Google定位的实现.
  3.   * Geolocation的详细信息请参见:
  4.   *
  5.   * href="" mce_href="">
  6.   *
  7.   */
  8. public class LocationAct extends Activity {
  9.      private TextView txtInfo;
  10.      public void onCreate(Bundle savedInstanceState) {
  11.          super.onCreate(savedInstanceState);
  12.          setContentView(R.layout.main);
  13.          Button btn = (Button) findViewById(R.id.btnStart);
  14.          txtInfo = (TextView) findViewById(R.id.txtInfo);
  15.          btn.setOnClickListener(new Button.OnClickListener() {
  16.              public void onClick(View view) {
  17.                  getLocation();
  18.              }
  19.          });
  20.      }
  21.      private void getLocation() {
  22.          TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
  23.          GsmCellLocation gsmCell = (GsmCellLocation) tm.getCellLocation();
  24.          int cid = gsmCell.getCid();
  25.          int lac = gsmCell.getLac();
  26.          String netOperator = tm.getNetworkOperator();
  27.          int mcc = Integer.valueOf(netOperator.substring(0, 3));
  28.          int mnc = Integer.valueOf(netOperator.substring(3, 5));
  29.          JSONObject holder = new JSONObject();
  30.          JSONArray array = new JSONArray();
  31.          JSONObject data = new JSONObject();
  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 (JSONException e) {
  46.              e.printStackTrace();
  47.          }
  48.          DefaultHttpClient client = new DefaultHttpClient();
  49.          HttpPost httpPost = new HttpPost("");
  50.          StringEntity stringEntity = null;
  51.          try {
  52.              stringEntity = new StringEntity(holder.toString());
  53.          } catch (UnsupportedEncodingException e) {
  54.              e.printStackTrace();
  55.          }
  56.          httpPost.setEntity(stringEntity);
  57.          HttpResponse httpResponse = null;
  58.          try {
  59.              httpResponse = client.execute(httpPost);
  60.          } catch (ClientProtocolException e) {
  61.              e.printStackTrace();
  62.          } catch (IOException e) {
  63.              e.printStackTrace();
  64.          }
  65.          HttpEntity httpEntity = httpResponse.getEntity();
  66.          InputStream is = null;
  67.          try {
  68.              is = httpEntity.getContent();
  69.          } catch (IllegalStateException e) {
  70.              e.printStackTrace();
  71.          } catch (IOException e) {
  72.              // TODO Auto-generated catch block
  73.              e.printStackTrace();
  74.          }
  75.          InputStreamReader isr = new InputStreamReader(is);
  76.          BufferedReader reader = new BufferedReader(isr);
  77.          StringBuffer stringBuffer = new StringBuffer();
  78.          try {
  79.              String result = "";
  80.              while ((result = reader.readLine()) != null) {
  81.                  stringBuffer.append(result);
  82.              }
  83.          } catch (IOException e) {
  84.              e.printStackTrace();
  85.          }
  86.          txtInfo.setText(stringBuffer.toString());
  87.      }
  88. }
第二种通过严格的GPS来定位,引用文章地址:http://www.cnblogs.com/wisekingokok/archive/2011/09/06/2168479.html,这里只引用代码
 

通过严格的GPS来定位

  1. public class MainActivity extends Activity {
  2.      private LocationManager locationManager;
  3.      private GpsStatus gpsstatus;
  4.      @Override
  5.      public void onCreate(Bundle savedInstanceState) {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.main);
  8.         
  9.         //获取到LocationManager对象
  10.         locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
  11.         
  12.         //根据设置的Criteria对象,获取最符合此标准的provider对象
  13.         String currentProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
  14.         
  15.         //根据当前provider对象获取最后一次位置信息
  16.         Location currentLocation = locationManager.getLastKnownLocation(currentProvider);
  17.         //如果位置信息为null,则请求更新位置信息
  18.         if(currentLocation == null){
  19.             locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener);
  20.         }
  21.         //增加GPS状态监听器
  22.         locationManager.addGpsStatusListener(gpsListener);
  23.         
  24.         //直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度
  25.         //每隔10秒获取一次位置信息
  26.         while(true){
  27.             currentLocation = locationManager.getLastKnownLocation(currentProvider);
  28.             if(currentLocation != null){
  29.                 Log.d("Location", "Latitude: " + currentLocation.getLatitude());
  30.                 Log.d("Location", "location: " + currentLocation.getLongitude());
  31.                 break;
  32.             }else{
  33.                 Log.d("Location", "Latitude: " + 0);
  34.                 Log.d("Location", "location: " + 0);
  35.             }
  36.             try {
  37.                 Thread.sleep(10000);
  38.             } catch (InterruptedException e) {
  39.                  Log.e("Location", e.getMessage());
  40.             }
  41.         }
  42.      }
  43.      
  44.      private GpsStatus.Listener gpsListener = new GpsStatus.Listener(){
  45.          //GPS状态发生变化时触发
  46.          @Override
  47.          public void onGpsStatusChanged(int event) {
  48.              //获取当前状态
  49.              gpsstatus=locationManager.getGpsStatus(null);
  50.              switch(event){
  51.                  //第一次定位时的事件
  52.                  case GpsStatus.GPS_EVENT_FIRST_FIX:
  53.                      break;
  54.                  //开始定位的事件
  55.                  case GpsStatus.GPS_EVENT_STARTED:
  56.                      break;
  57.                  //发送GPS卫星状态事件
  58.                  case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
  59.                      Toast.makeText(MainActivity.this, "GPS_EVENT_SATELLITE_STATUS", Toast.LENGTH_SHORT).show();
  60.                      Iterable<GpsSatellite> allSatellites = gpsstatus.getSatellites();
  61.                      Iterator<GpsSatellite> it=allSatellites.iterator();
  62.                      int count = 0;
  63.                      while(it.hasNext())
  64.                      {
  65.                          count++;
  66.                      }
  67.                      Toast.makeText(MainActivity.this, "Satellite Count:" + count, Toast.LENGTH_SHORT).show();
  68.                      break;
  69.                  //停止定位事件
  70.                  case GpsStatus.GPS_EVENT_STOPPED:
  71.                      Log.d("Location", "GPS_EVENT_STOPPED");
  72.                      break;
  73.              }
  74.          }
  75.      };
  76.      
  77.      
  78.      //创建位置监听器
  79.      private LocationListener locationListener = new LocationListener(){
  80.          //位置发生改变时调用
  81.          @Override
  82.          public void onLocationChanged(Location location) {
  83.              Log.d("Location", "onLocationChanged");
  84.          }
  85.  
  86.          //provider失效时调用
  87.          @Override
  88.          public void onProviderDisabled(String provider) {
  89.              Log.d("Location", "onProviderDisabled");
  90.          }
  91.  
  92.          //provider启用时调用
  93.          @Override
  94.          public void onProviderEnabled(String provider) {
  95.              Log.d("Location", "onProviderEnabled");
  96.          }
  97.  
  98.          //状态改变时调用
  99.          @Override
  100.          public void onStatusChanged(String provider, int status, Bundle extras) {
  101.              Log.d("Location", "onStatusChanged");
  102.          }
  103.      };
  104.  }
第三种主要是通过网络的方式来定位,引用文章地址:http://www.cnblogs.com/wisekingokok/archive/2011/09/05/2167755.html,这里只写代码
 

通过网络的方式来定位

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


阅读(570) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~