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 2019/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(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

发布了154 篇原创文章 · 获赞 36 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/yijiaodingqiankun/article/details/88581358