第一步,申明权限。(5.0之后权限需要动态申请,具体代码和这个问题无关就不贴出来了)
<uses-permissionandroid:name=\"android.permission.ACCESS_FINE_LOCATION\"/>
<uses-permissionandroid:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>
第二步通过LocationManager类获取位置信息,下面是一个封装好的工具类
**
*CreatedbyDELLzhanghuirongon2019/3/15.
*获取当前位置信息
*/
publicclassMyLocationUtil{
privatestaticStringprovider;
publicstaticLocationgetMyLocation(){
//获取当前位置信息
//获取定位服务
LocationManagerlocationManager=(LocationManager)MyApp.getContext().getSystemService(Context.LOCATION_SERVICE);
//获取当前可用的位置控制器
List<String>list=locationManager.getProviders(true);
if(list.contains(locationManager.GPS_PROVIDER)){
//GPS位置控制器
provider=locationManager.GPS_PROVIDER;//GPS定位
}elseif(list.contains(locationManager.NETWORK_PROVIDER)){
//网络位置控制器
provider=locationManager.NETWORK_PROVIDER;//网络定位
}
if(provider!=null){
if(ActivityCompat.checkSelfPermission(MyApp.getContext(),Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED&&ActivityCompat.checkSelfPermission(MyApp.getContext(),Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
//TODO:Considercalling
//ActivityCompat#requestPermissions
//heretorequestthemissingpermissions,andthenoverriding
//publicvoidonRequestPermissionsResult(intrequestCode,String[]permissions,
//int[]grantResults)
//tohandlethecasewheretheusergrantsthepermission.Seethedocumentation
//forActivityCompat#requestPermissionsformoredetails.
returnnull;
}
LocationlastKnownLocation=locationManager.getLastKnownLocation(provider);
returnlastKnownLocation;
}else{
ToastUtils.makeText(\"请检查网络或GPS是否打开\");
}
returnnull;
}
}
第三步(其实到上一步这个问题已经解决了,这个算扩展吧)将位置信息转换成地址信息。
在高德或者百度地图开发者平台申请访问api许可。将第二步获取到的经纬度信息上传查询对应坐标信息。因为百度和高德用的不是同一个坐标系,查询时仔细看官方API。
直接通过安卓的原生接口获取一个gps的位置意义不是很大。这个数据在一定的坐标系上才有意义。建议去高德的开发平台注册个帐号,引入sdk来做,地理位置与地理位置解析的概念先了解下吧。
//第一步先获取LocationManager的对象LocationManagerGpsManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);//通过LocationManager的对象来获取到Location的信息。Locationlocation=GpsManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);//Location中经常用到的有以下几种:/*location.getAccuracy();精度location.getAltitude();高度:海拔location.getBearing();导向location.getSpeed();速度location.getLatitude();纬度location.getLongitude();经度location.getTime();UTC时间以毫秒计*/注:需要添加使用权限的哦
本文仅代表作者观点,版权归属原创作者,如需转载请在文中标注来源及作则名字。
免责声明:本文系转载编辑文章,仅做分享只用,如有疑问请联系邮箱:110@zbj.com
随着安卓开发相关岗位需求越来越大,安卓开发人员供不应求。对于求职者来说,在这样的情况下,选择进入安卓开发行业,成为一名安卓开发工程师,就业前景是非常光明的。很多同学都在问,学安卓开发需要什么基础,小编给大家提出几点建议!
AndroidStudio数据库教程?
Android开发怎么查看和管理sqlite数据库?
android开发怎么获得手机的gps?
android中怎么做单元测试?