Android获取当前位置(GPS和网络定位)
16lz
2021-01-24
1.添加定位权限
2.下面是我封装的工具类** * Created by DELL zhanghuirong on 2019/3/15. * 获取当前位置信息 */public class MyLocationUtil { private static String provider; public static Location getMyLocation() {// 获取当前位置信息 //获取定位服务 LocationManager locationManager = (LocationManager) MyApp.getContext().getSystemService(Context.LOCATION_SERVICE); //获取当前可用的位置控制器 List list = locationManager.getProviders(true); if (list.contains(locationManager.GPS_PROVIDER)) {// GPS位置控制器 provider = locationManager.GPS_PROVIDER;//GPS定位 } else if (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: Consider calling // ActivityCompat#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 ActivityCompat#requestPermissions for more details. return null; } Location lastKnownLocation = locationManager.getLastKnownLocation(provider); return lastKnownLocation; } else { ToastUtils.makeText("请检查网络或GPS是否打开"); } return null; }}
3.通过百度地图提供的Web服务API,进行反地理编码,将我们的经纬度转换成正常的位置信息
4.
5.6.
7.
我用的网络请求框架是Retrofit2,遇到的坑是在参数拼接上
坑就是红框里的经纬度拼接
注意:我没写监听,如果需要你自己添加。————————经过本人实际测试,发现,在我写代码的地方,定位是可以用的,我拿着手机到其他地方(几公里以外的地方),打开发现不显示定位,希望你们实际测试完能给评价或者留言告诉我问题所在,最后,谢谢大家。
参考链接:https://blog.csdn.net/mingjiezuo/article/details/79755357
(这个是有监听的链接)https://blog.csdn.net/yelin042/article/details/78199409
更多相关文章
- android 音量调节时,嘟 的 发声位置
- 如何把应用安装到sd卡中
- Android(安卓)- adb shell Permission denied
- ArcGIS for Android(安卓)如何将经纬度坐标转换成投影坐标
- Android(安卓)layout、onLayout 一些简要说明
- address2line 定位 Android(安卓)c++奔溃位置
- android中使用百度定位sdk实时的计算移动距离
- android中如何获取经纬度?
- 经纬度转度分秒 Java/Android