Android开发使用LocationManager实现定位服务
做项目需要获取经纬度信息,学习了下android自带的定位API,简单实现了一下,这里记录一下。废话不多说,先上代码:
private String locationStr = "";private String message = "";private static final int REQUEST_CODE = 10;private void getLocation() {if (Build.VERSION.SDK_INT >= 23) {// android6 执行运行时权限if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling // Activity#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for Activity#requestPermissions for more details.ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE); }}Criteria criteria = new Criteria();criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度,如果设置为高精度,依然获取不了location。 criteria.setAltitudeRequired(false);//不要求海拔 criteria.setBearingRequired(false);//不要求方位 criteria.setCostAllowed(true);//允许有花费 criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗 //获取LocationManager LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);// 获取最好的定位方式 String provider = locationManager.getBestProvider(criteria, true); // true 代表从打开的设备中查找 // 获取所有可用的位置提供器 List<String> providerList = locationManager.getProviders(true);// 测试一般都在室内,这里颠倒了书上的判断顺序 if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {provider = LocationManager.NETWORK_PROVIDER;} else if (providerList.contains(LocationManager.GPS_PROVIDER)) {provider = LocationManager.GPS_PROVIDER;} else {// 当没有可用的位置提供器时,弹出Toast提示用户 Toast.makeText(this, "Please Open Your GPS or Location Service", Toast.LENGTH_SHORT).show();return;}LocationListener locationListener = new LocationListener(){//当位置改变的时候调用 @Override public void onLocationChanged(Location location) {//经度 double longitude = location.getLongitude();//纬度 double latitude = location.getLatitude();//海拔 double altitude = location.getAltitude();locationStr = longitude+"_"+latitude;launcher.callExternalInterface("getLocationSuccess", locationStr);}//当GPS状态发生改变的时候调用 @Override public void onStatusChanged(String provider, int status, Bundle extras) {switch (status) {case LocationProvider.AVAILABLE:message = "当前GPS为可用状态!";break;case LocationProvider.OUT_OF_SERVICE:message = "当前GPS不在服务内!";break;case LocationProvider.TEMPORARILY_UNAVAILABLE:message = "当前GPS为暂停服务状态!";break;}launcher.callExternalInterface("GPSStatusChanged", message);}//GPS开启的时候调用 @Override public void onProviderEnabled(String provider) {message = "GPS开启了!";launcher.callExternalInterface("GPSOpenSuccess", message);}//GPS关闭的时候调用 @Override public void onProviderDisabled(String provider) {message = "GPS关闭了!";launcher.callExternalInterface("GPSClosed", message);}}; //获取上次的location Location location = locationManager.getLastKnownLocation(provider);
/** * 参1:选择定位的方式 * 参2:定位的间隔时间 * 参3:当位置改变多少时进行重新定位 * 参4:位置的回调监听 */
locationManager.requestLocationUpdates(provider, 10000, 0, locationListener); while(location == null){ location = locationManager.getLastKnownLocation(provider); } //移除更新监听 locationManager.removeUpdates(locationListener); if (location != null) { //不为空,显示地理位置经纬度 //经度 double longitude = location.getLongitude(); //纬度 double latitude = location.getLatitude(); //海拔 double altitude = location.getAltitude(); locationStr = longitude+ "_"+latitude; launcher.callExternalInterface( "getLocationSuccess", locationStr); } }
/** * 获取权限结果 */ @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);if (requestCode == REQUEST_CODE) {if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {// Permission Granted准许getLocation();} else {// Permission Denied拒绝 }} }
简单说明一下,getLocation()方法实现定位的一系列操作,但是安卓要调服务是需要验证权限的,所以要复写onRequestPermissionsResult方法。
关键点:
//获取上次的location
Location location = locationManager.getLastKnownLocation(provider);
获取最近一次的有效location,如果没有,则返回null。也就是说最近一次必须获取过定位才能得到lastLocation。第一次登录或者新安装的app是会返回null的。
那么问题来了,如何获取第一次的定位信息呢?可以通过下面这个方法注册请求新的位置信息:
locationManager.requestLocationUpdates(provider, 10000, 0, locationListener);
其中,provider 是使用的定位服务商,主要有
LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER, LocationManager.PASSIVE_PROVIDER
第一个是网络定位,第二个是GPS定位,第三个是直接取缓存。LocationManager本身提供了选择最好的provider的方法:
// 获取最好的定位方式 String provider = locationManager.getBestProvider(criteria, true); // true 代表从打开的设备中查找
但是我在上面选择provider时做了一个检查的操作:
// 获取所有可用的位置提供器 List<String> providerList = locationManager.getProviders(true); // 测试一般都在室内,这里颠倒了书上的判断顺序 if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {provider = LocationManager.NETWORK_PROVIDER; } else if (providerList.contains(LocationManager.PASSIVE_PROVIDER)) {provider = LocationManager.GPS_PROVIDER; } else {// 当没有可用的位置提供器时,弹出Toast提示用户 Toast.makeText(this, "Please Open Your GPS or Location Service", Toast.LENGTH_SHORT).show();return; }
原因是API本身是GPS优先的,这样在室内测试时会出现bestprovider得到的是GPS方式,但是却无法定位的情况(室内GPS信号很弱,基本不可用)。所以我改成了优先选择网络定位,然后再选择GPS定位。实际使用时可以去掉该段操作。
另外,locationListener是注册的监听事件。其中我们要关注的是
public void onLocationChanged(Location location)
这个方法会监听上面的requestLocationUpdates,获取到新的位置信息就会回调该方法,所以大家可以再这个方法里处理获取到的location。
不过,这个定位有一个很大的问题,那就是对于部分安卓设备,第一次获取location时,会在locationManager.requestLocationUpdates处堵塞,导致程序一直卡在这里,迟迟得不到onLocationChanged的回调。我测试了安卓5,6, 7的设备,其中两个android5.1.1的设备一直都获取不到location,这就导致该定位无法在此设备上使用。查了各种网站,发现有两个网友遇到了同样的问题,但是取没有解决:https://segmentfault.com/q/1010000004477439/a-1020000006144410。
但是有一个奇怪的现象,就是我在android5.1.1的设备上测试的时候,偶尔是可以得到一次location的,但这个几率极低。网上有说需要等待一段时间,但是我等了个把小时都不行。
另外我也试了google的FusedLocationProviderClient方法,也是堵塞在requestLocationUpdates,实在是郁闷。由于我做的是一个海外的项目,所以什么百度API,腾讯API就不用想了。
这里贴出来也是希望大神们看到之后能够指正,并希望能帮忙解决上面这个问题,大家共同进步。
Android开发使用LocationManager实现定位服务相关推荐
- Android开发之百度地图定位打卡
Android开发之百度地图定位打卡 一.效果图 二.下载百度地图SDK 三.代码实现 1.布局文件(activity_main) 2.布局文件(activity_map) 3.在res文件夹下新建m ...
- Android开发中虚拟位置定位、应用双开、IP代理检测
Android开发中虚拟位置定位.应用双开.IP代理检测 1.虚拟位置定位.应用双开原理 目前市面上的多开App的原理类似,都是以新进程运行被多开的App,并hook各类系统函数,使被多开的App认为 ...
- Android开发之百度地图定位
Android开发之百度地图定位 一.效果图 二.下载百度地图SDK 1.打开[百度地图](https://lbsyun.baidu.com/index.php?title=%E9%A6%96%E9% ...
- Android开发:LocationManager获取经纬度及定位过程(附demo)
其实LocationManager,Geocoder这些Android API给我们提供的这些类就可以满足了.下面笔者就来讲讲如何利用LocationManager获取经纬度,并利用Geocoder将 ...
- Android开发如何定制framework层服务
刚刚跨完年,新年第一篇文章,那么今天将对Android开发framework中间层的服务定制使用作个总结.首先我们先导入Android平台源码framework层的代码到开发工具eclipse中,代码 ...
- Android开发之高德地图定位成功返回的定位信息
/*** 定位监听*/AMapLocationListener locationListener = new AMapLocationListener() {@Overridepublic void ...
- Android基于高德地图实时定位服务
Service功能有:实时定位(后台进行) Service不会,去百度谷歌 功能有 实时定位(30秒间隔) 判断是否在规定的时间段内 判断距离是否大于规定的距离 判断服务是否在开启的状态 服务代码:L ...
- Android开发之百度地图定位以及简单覆盖物的实现
直接上代码: 先看下效果图: 我这里主要做了三个功能: 1.一秒钟实时定位功能: 2.添加任意经纬度地点到地图上: 3.判断朝阳门是否在本人定位范围1000米内: 百度地图初始化方法: DemoApp ...
- Android开发实现高德地图定位详解
一. 要实现高德地图定位呢,首先需要做好以下几步准备: 1. 在高德开放平台注册帐号 注册地址:http://lbs.amap.com 2. 在开发中下载Android平台下的地图SDK和定位S ...
最新文章
- 全景图拼接算法实现与改进
- 第一章 内核模块 elf文件
- 探讨:COCO2017数据集中包含很多目标被标注为一个框bbox,是标注错误吗?
- pps服务器未响应_服务响应时间与分布
- python交互式和文件式区别_Python中的交互式数据可视化与Bokeh(系列五)
- c oracle time,在C/C++中添加1个月到time_t的简单方法
- 双显示器设置:如何设置一台电脑两个显示器
- Netcdf中时间的格式化
- “弱肉强食,月半者为王” | OpenDILab推出多智能体博弈环境Go-Bigger
- php语言开始和结束分别为,0055 PHP语言简介和HelloWorld
- asp.net 文件下载(txt,rar,pdf,word,excel,ppt)
- 进销存软件定制开发怎么做?
- LMDB:闪电内存映射数据库管理器
- html 长度太长截断,HTML CSS 表格换行禁止 超出指定长度自动截断
- HttpServletRequest获取中文参数乱码问题
- 图像处理---LoMo
- noi 2017 简要题解
- 如何对接好线上支付?
- SOPHON BM1684芯片解码性能以及支持的文件格式
- windows异常处理