最近在看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,下载只是实现定位的代码

/** * Google定位的实现.<br/> * Geolocation的详细信息请参见:<br/> * <a * href="http://code.google.com/apis/gears/geolocation_network_protocol.html" mce_href="http://code.google.com/apis/gears/geolocation_network_protocol.html"> * http://code.google.com/apis/gears/geolocation_network_protocol.html</a> */
public class LocationAct extends Activity {  private TextView txtInfo;  public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  Button btn = (Button) findViewById(R.id.btnStart);  txtInfo = (TextView) findViewById(R.id.txtInfo);  btn.setOnClickListener(new Button.OnClickListener() {  public void onClick(View view) {  getLocation();  }  });  }  private void getLocation() {  TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);  GsmCellLocation gsmCell = (GsmCellLocation) tm.getCellLocation();  int cid = gsmCell.getCid();  int lac = gsmCell.getLac();  String netOperator = tm.getNetworkOperator();  int mcc = Integer.valueOf(netOperator.substring(0, 3));  int mnc = Integer.valueOf(netOperator.substring(3, 5));  JSONObject holder = new JSONObject();  JSONArray array = new JSONArray();  JSONObject data = new JSONObject();  try {  holder.put("version", "1.1.0");  holder.put("host", "maps.google.com");  holder.put("address_language", "zh_CN");  holder.put("request_address", true);  holder.put("radio_type", "gsm");  holder.put("carrier", "HTC");  data.put("cell_id", cid);  data.put("location_area_code", lac);  data.put("mobile_countyr_code", mcc);  data.put("mobile_network_code", mnc);  array.put(data);  holder.put("cell_towers", array);  } catch (JSONException e) {  e.printStackTrace();  }  DefaultHttpClient client = new DefaultHttpClient();  HttpPost httpPost = new HttpPost("http://www.google.com/loc/json");  StringEntity stringEntity = null;  try {  stringEntity = new StringEntity(holder.toString());  } catch (UnsupportedEncodingException e) {  e.printStackTrace();  }  httpPost.setEntity(stringEntity);  HttpResponse httpResponse = null;  try {  httpResponse = client.execute(httpPost);  } catch (ClientProtocolException e) {  e.printStackTrace();  } catch (IOException e) {  e.printStackTrace();  }  HttpEntity httpEntity = httpResponse.getEntity();  InputStream is = null;  try {  is = httpEntity.getContent();  } catch (IllegalStateException e) {  e.printStackTrace();  } catch (IOException e) {  // TODO Auto-generated catch block
             e.printStackTrace();  }  InputStreamReader isr = new InputStreamReader(is);  BufferedReader reader = new BufferedReader(isr);  StringBuffer stringBuffer = new StringBuffer();  try {  String result = "";  while ((result = reader.readLine()) != null) {  stringBuffer.append(result);  }  } catch (IOException e) {  e.printStackTrace();  }  txtInfo.setText(stringBuffer.toString());  }
}

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

public class MainActivity extends Activity {private LocationManager locationManager;private GpsStatus gpsstatus;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//获取到LocationManager对象
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);//根据设置的Criteria对象,获取最符合此标准的provider对象
        String currentProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();//根据当前provider对象获取最后一次位置信息
        Location currentLocation = locationManager.getLastKnownLocation(currentProvider);//如果位置信息为null,则请求更新位置信息
        if(currentLocation == null){locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener);}//增加GPS状态监听器
        locationManager.addGpsStatusListener(gpsListener);//直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度//每隔10秒获取一次位置信息
        while(true){currentLocation = locationManager.getLastKnownLocation(currentProvider);if(currentLocation != null){Log.d("Location", "Latitude: " + currentLocation.getLatitude());Log.d("Location", "location: " + currentLocation.getLongitude());break;}else{Log.d("Location", "Latitude: " + 0);Log.d("Location", "location: " + 0);}try {Thread.sleep(10000);} catch (InterruptedException e) {Log.e("Location", e.getMessage());}}}private GpsStatus.Listener gpsListener = new GpsStatus.Listener(){//GPS状态发生变化时触发
         @Overridepublic void onGpsStatusChanged(int event) {//获取当前状态
             gpsstatus=locationManager.getGpsStatus(null);switch(event){//第一次定位时的事件
                 case GpsStatus.GPS_EVENT_FIRST_FIX:break;//开始定位的事件
                 case GpsStatus.GPS_EVENT_STARTED:break;//发送GPS卫星状态事件
                 case GpsStatus.GPS_EVENT_SATELLITE_STATUS:Toast.makeText(MainActivity.this, "GPS_EVENT_SATELLITE_STATUS", Toast.LENGTH_SHORT).show();Iterable<GpsSatellite> allSatellites = gpsstatus.getSatellites();   Iterator<GpsSatellite> it=allSatellites.iterator(); int count = 0;while(it.hasNext())   {   count++;}Toast.makeText(MainActivity.this, "Satellite Count:" + count, Toast.LENGTH_SHORT).show();break;//停止定位事件
                 case GpsStatus.GPS_EVENT_STOPPED:Log.d("Location", "GPS_EVENT_STOPPED");break;}}};//创建位置监听器
     private LocationListener locationListener = new LocationListener(){//位置发生改变时调用
         @Overridepublic void onLocationChanged(Location location) {Log.d("Location", "onLocationChanged");}//provider失效时调用
         @Overridepublic void onProviderDisabled(String provider) {Log.d("Location", "onProviderDisabled");}//provider启用时调用
         @Overridepublic void onProviderEnabled(String provider) {Log.d("Location", "onProviderEnabled");}//状态改变时调用
         @Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {Log.d("Location", "onStatusChanged");}};}

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

package com.test;import java.io.IOException;import java.util.List;import android.app.Activity;import android.location.Address;import android.location.Criteria;import android.location.Geocoder;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.Bundle;import android.util.Log;import android.widget.Toast;public class MainActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//获取到LocationManager对象
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);//创建一个Criteria对象
        Criteria criteria = new Criteria();//设置粗略精确度
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//设置是否需要返回海拔信息
        criteria.setAltitudeRequired(false);//设置是否需要返回方位信息
        criteria.setBearingRequired(false);//设置是否允许付费服务
        criteria.setCostAllowed(true);//设置电量消耗等级
        criteria.setPowerRequirement(Criteria.POWER_HIGH);//设置是否需要返回速度信息
        criteria.setSpeedRequired(false);//根据设置的Criteria对象,获取最符合此标准的provider对象
        String currentProvider = locationManager.getBestProvider(criteria, true);Log.d("Location", "currentProvider: " + currentProvider);//根据当前provider对象获取最后一次位置信息
        Location currentLocation = locationManager.getLastKnownLocation(currentProvider);//如果位置信息为null,则请求更新位置信息
        if(currentLocation == null){locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener);}//直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度//每隔10秒获取一次位置信息
        while(true){currentLocation = locationManager.getLastKnownLocation(currentProvider);if(currentLocation != null){Log.d("Location", "Latitude: " + currentLocation.getLatitude());Log.d("Location", "location: " + currentLocation.getLongitude());break;}else{Log.d("Location", "Latitude: " + 0);Log.d("Location", "location: " + 0);}try {Thread.sleep(10000);} catch (InterruptedException e) {Log.e("Location", e.getMessage());}}//解析地址并显示
        Geocoder geoCoder = new Geocoder(this);try {int latitude = (int) currentLocation.getLatitude();int longitude = (int) currentLocation.getLongitude();List<Address> list = geoCoder.getFromLocation(latitude, longitude, 2);for(int i=0; i<list.size(); i++){Address address = list.get(i); Toast.makeText(MainActivity.this, address.getCountryName() + address.getAdminArea() + address.getFeatureName(), Toast.LENGTH_LONG).show();}} catch (IOException e) {Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();}}//创建位置监听器
     private LocationListener locationListener = new LocationListener(){//位置发生改变时调用
         @Overridepublic void onLocationChanged(Location location) {Log.d("Location", "onLocationChanged");Log.d("Location", "onLocationChanged Latitude" + location.getLatitude());Log.d("Location", "onLocationChanged location" + location.getLongitude());}//provider失效时调用
         @Overridepublic void onProviderDisabled(String provider) {Log.d("Location", "onProviderDisabled");}//provider启用时调用
         @Overridepublic void onProviderEnabled(String provider) {Log.d("Location", "onProviderEnabled");}//状态改变时调用
         @Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {Log.d("Location", "onStatusChanged");}};}

Nothing is impossible!^oudi&orange^

原文章地址:http://www.cnblogs.com/oudi/archive/2012/03/22/2411509.html

android 三种定位方式相关推荐

  1. android 三种定位方式 介绍

    三种获取手机的位置的方式_20 1.网络定位(network).前提是必须连上网络:wifi.3G.2G: 获取到IP地址 例如:传美版QQ,彩虹版QQ,珊瑚虫版QQ,就有一个功能显示对方的IP: 根 ...

  2. 百度地图三种定位方式测试(高精度、低功耗、仅用设备)

    百度地图三种定位方式测试(高精度.低功耗.仅用设备) Android定位SDK自v7.0版本起,按照附加功能不同,向开发者提供了四种不同类型的定位开发包,可根据不同需求,自有选择所需类型的开发包使用. ...

  3. html5边框顶格,CSS 三种定位方式以及格式化上下文详解 》 html5jscss

    常规流( Normal flow ) 之称之为常规流,是因为这是相对于后面的浮动和绝对定位的一个概念,浮动和绝对定位元素都脱离了当前的常规流. 在 CSS2.1中,常规流包括块框( block box ...

  4. ios wifi 定位_iOS中三种定位方式

    手机基站定位 原理 每个手机基站都有一个标识符,iPhone或3G iPad可以搜集周围所有收到信号的基站和它们的标识符,通过联网发送到苹果云端服务器,再由服务器根据这些基站的的位置信息查询并计算出当 ...

  5. Android 的三种定位方式

    转载自:http://blog.csdn.net/luosiye312/article/details/50562309#comments Android 定位大致分为三大类:GPS定位:Networ ...

  6. ios wifi 定位_iOS 中的三种定位方式

    1.手机基站定位 原理: 每个手机基站都有一个标识符,iPhone或3G iPad可以搜集周围所有收到信号的基站和它们的标识符,通过联网发送到苹果云端服务器,再由服务器根据这些基站的的位置信息查询并计 ...

  7. css的三种定位方式使用探讨

    css 3种类型定位方式,进行控制页面布局:普通定位,浮动定位,绝对定位. 默认使用普通流技术再页面中布局元素,希望表现与普通流不同,另外两个特性position和float 具体实例 复制代码 代码 ...

  8. android三种载入图片方式

    package smalt.music.utils;    import android.graphics.Bitmap;  import android.graphics.BitmapFactory ...

  9. Android 三种拨号方式(kotlin)

    文章目录 前置代码 直接拨打电话 跳转页面拨打电话 反射方式拨打电话 前置代码 // 获取界面上输入的电话号码 val phoneNumber = findViewById<EditText&g ...

最新文章

  1. VLOG丨树莓派Raspberry Pi 3安装PLEX并挂载USB硬盘打造最牛的微型家庭影音服务器2018...
  2. php 接口的定义与实现,PHP接口定义与用法示例
  3. 【白话机器学习】算法理论+实战之K近邻算法
  4. 分支程序与循环程序设计-汇编实验二
  5. 最后关于Pipeline完整的图如下:
  6. 视频隐身衣:物体移除、去水印、后期处理毫无痕迹
  7. 网络安全基础——用户与组管理
  8. 机器学习 - 贝叶斯网络
  9. 超强wifi6路由器推荐!不强你打我!
  10. html实现图片轮播切换箭头,最简单jquery实现带左右箭头和数字焦点的图片轮播...
  11. java feature envy_《重构-改善既有代码的设计 第3章代码的坏味道》学习笔记
  12. 面试官问:为什么 Java 线程没有Running状态?我懵了
  13. java十进制转换成二进制
  14. 【数字图像处理】Python实现图像变换/沃尔什哈达玛变换(WHT,Walsh-Hadamard Transform)
  15. 2020新冠疫情下如何防范恶意软件攻击避免数据泄露?
  16. excel: 单元格格式修改及绘图
  17. 支付宝即时到账在线语音音效生成器html源码(地球最强装13)
  18. Linux内核安装后reboot选择,Linux内核配置选项 参考(3)
  19. mysql同时更新2个表_mysql中同时update更新多个表
  20. Oracle学习之基础

热门文章

  1. 直流电机的电流、转速、电压的关系
  2. GcExcel for java 6.0 简单例子 -jar has been cracked
  3. 22考研清华905机械设计基础上岸经验分享
  4. 大学生书店网页设计制作 简单静态在线书店HTML网页作品 小说书籍网页作业成品 学生期末作业网站模板
  5. Go的宕机与宕机恢复
  6. uniapp组件-Card卡片
  7. 一万字! 中大形企业网络部署架构(链路聚合 mstp+vrrp ap+ac 防火墙 ospf )
  8. HPA的target显示unknown
  9. 嵌入式测试大赛预选赛
  10. GIS开发之二维地下管线综合管理系统(Arcgis)第一节 总体介绍