当前位置:首页 > 问答 > android开发怎么获得手机的gps

android开发怎么获得手机的gps

  • 2023-05-14 21:58:21

android开发怎么获得手机的gps?

android开发怎么获得手机的gps

第一步,申明权限。(5.0之后权限需要动态申请,具体代码和这个问题无关就不贴出来了)

<!--定位权限--

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/

第二步通过LocationManager类获取位置信息,下面是一个封装好的工具类

**

* 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;

}

}

第三步(其实到上一步这个问题已经解决了,这个算扩展吧)将位置信息转换成地址信息。

在高德或者百度地图开发者平台申请访问api许可。将第二步获取到的经纬度信息上传查询对应坐标信息。因为百度和高德用的不是同一个坐标系,查询时仔细看官方API。

//第一步先获取LocationManager的对象LocationManager GpsManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); //通过LocationManager的对象来获取到Location的信息。Location location = GpsManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //Location中经常用到的有以下几种:/* location.getAccuracy(); 精度 location.getAltitude(); 高度 : 海拔 location.getBearing(); 导向 location.getSpeed(); 速度 location.getLatitude(); 纬度 location.getLongitude(); 经度 location.getTime(); UTC时间 以毫秒计*/ 注:需要添加使用权限的哦

直接通过安卓的原生接口获取一个gps的位置意义不是很大。这个数据在一定的坐标系上才有意义。建议去高德的开发平台注册个帐号,引入sdk来做,地理位置与地理位置解析的概念先了解下吧。

热门阅读

最新文章