100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Android获取当前位置(GPS和网络定位)

Android获取当前位置(GPS和网络定位)

时间:2021-01-17 17:11:06

相关推荐

Android获取当前位置(GPS和网络定位)

1.添加定位权限

<!--定位权限--><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

2.下面是我封装的工具类*** Created by DELL zhanghuirong on /3/15.* 获取当前位置信息*/public class MyLocationUtil {private static String provider;public static Location getMyLocation() {// 获取当前位置信息//获取定位服务LocationManager locationManager = (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定位} else if (list.contains(WORK_PROVIDER)) {// 网络位置控制器provider = WORK_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,遇到的坑是在参数拼接上

坑就是红框里的经纬度拼接

注意:我没写监听,如果需要你自己添加。————————经过本人实际测试,发现,在我写代码的地方,定位是可以用的,我拿着手机到其他地方(几公里以外的地方),打开发现不显示定位,希望你们实际测试完能给评价或者留言告诉我问题所在,最后,谢谢大家。

参考链接:/mingjiezuo/article/details/79755357

(这个是有监听的链接)/yelin042/article/details/78199409

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。