Android开发使用LocationManager实现定位服务

做项目需要获取经纬度信息,学习了下android自带的定位API,简单实现了一下,这里记录一下。废话不多说,先上代码:

  private String locationStr = "";
    private String message = "";
    private static final int REQUEST_CODE = 10;

    private void getLocation() {
        if (Build.VERSION.SDK_INT >= 23) {// android6 执行运行时权限
            if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#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 Activity#requestPermissions for more details.
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
            }
        }

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度,如果设置为高精度,依然获取不了location。
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(true);//允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
        //获取LocationManager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // 获取最好的定位方式
        String provider = locationManager.getBestProvider(criteria, true); // true 代表从打开的设备中查找

        // 获取所有可用的位置提供器
        List providerList = locationManager.getProviders(true);
        // 测试一般都在室内,这里颠倒了书上的判断顺序
        if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else {
            // 当没有可用的位置提供器时,弹出Toast提示用户
            Toast.makeText(this, "Please Open Your GPS or Location Service", Toast.LENGTH_SHORT).show();
            return;
        }

        LocationListener locationListener = new LocationListener(){
            //当位置改变的时候调用
            @Override
            public void onLocationChanged(Location location) {
                //经度
                double longitude = location.getLongitude();
                //纬度
                double latitude = location.getLatitude();

                //海拔
                double altitude = location.getAltitude();

                locationStr = longitude+"_"+latitude;
                launcher.callExternalInterface("getLocationSuccess", locationStr);
            }

            //当GPS状态发生改变的时候调用
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

                switch (status) {

                    case LocationProvider.AVAILABLE:
                        message = "当前GPS为可用状态!";
                        break;

                    case LocationProvider.OUT_OF_SERVICE:
                        message = "当前GPS不在服务内!";
                        break;

                    case LocationProvider.TEMPORARILY_UNAVAILABLE:
                        message = "当前GPS为暂停服务状态!";
                        break;

                }
                launcher.callExternalInterface("GPSStatusChanged", message);

            }

            //GPS开启的时候调用
            @Override
            public void onProviderEnabled(String provider) {
                message = "GPS开启了!";
                launcher.callExternalInterface("GPSOpenSuccess", message);

            }
            //GPS关闭的时候调用
            @Override
            public void onProviderDisabled(String provider) {
                message = "GPS关闭了!";
                launcher.callExternalInterface("GPSClosed", message);

            }
        };

        //获取上次的location
        Location location = locationManager.getLastKnownLocation(provider);
    
 /**
         * 参1:选择定位的方式
         * 参2:定位的间隔时间
         * 参3:当位置改变多少时进行重新定位
         * 参4:位置的回调监听
         */
locationManager.requestLocationUpdates(provider, 10000, 0, locationListener); while(location == null){ location = locationManager.getLastKnownLocation(provider); } //移除更新监听 locationManager.removeUpdates(locationListener); if (location != null) { //不为空,显示地理位置经纬度 //经度 double longitude = location.getLongitude(); //纬度 double latitude = location.getLatitude(); //海拔 double altitude = location.getAltitude(); locationStr = longitude+ "_"+latitude; launcher.callExternalInterface( "getLocationSuccess", locationStr); } }
/**
 * 获取权限结果
 */
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission Granted准许
            getLocation();
        } else {
            // Permission Denied拒绝
        }
    }
}

简单说明一下,getLocation()方法实现定位的一系列操作,但是安卓要调服务是需要验证权限的,所以要复写onRequestPermissionsResult方法。

关键点:

//获取上次的location

Location location = locationManager.getLastKnownLocation(provider);

获取最近一次的有效location,如果没有,则返回null。也就是说最近一次必须获取过定位才能得到lastLocation。第一次登录或者新安装的app是会返回null的。

那么问题来了,如何获取第一次的定位信息呢?可以通过下面这个方法注册请求新的位置信息:

locationManager.requestLocationUpdates(provider, 10000, 0, locationListener);
其中,provider 是使用的定位服务商,主要有
LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER, LocationManager.PASSIVE_PROVIDER

第一个是网络定位,第二个是GPS定位,第三个是直接取缓存。LocationManager本身提供了选择最好的provider的方法:

// 获取最好的定位方式
String provider = locationManager.getBestProvider(criteria, true); // true 代表从打开的设备中查找

但是我在上面选择provider时做了一个检查的操作:

// 获取所有可用的位置提供器
List providerList = locationManager.getProviders(true);
// 测试一般都在室内,这里颠倒了书上的判断顺序
if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
    provider = LocationManager.NETWORK_PROVIDER;
} else if (providerList.contains(LocationManager.PASSIVE_PROVIDER)) {
    provider = LocationManager.GPS_PROVIDER;
} else {
    // 当没有可用的位置提供器时,弹出Toast提示用户
    Toast.makeText(this, "Please Open Your GPS or Location Service", Toast.LENGTH_SHORT).show();
    return;
}

原因是API本身是GPS优先的,这样在室内测试时会出现bestprovider得到的是GPS方式,但是却无法定位的情况(室内GPS信号很弱,基本不可用)。所以我改成了优先选择网络定位,然后再选择GPS定位。实际使用时可以去掉该段操作。

另外,locationListener是注册的监听事件。其中我们要关注的是

public void onLocationChanged(Location location)

这个方法会监听上面的requestLocationUpdates,获取到新的位置信息就会回调该方法,所以大家可以再这个方法里处理获取到的location。

不过,这个定位有一个很大的问题,那就是对于部分安卓设备,第一次获取location时,会在locationManager.requestLocationUpdates处堵塞,导致程序一直卡在这里,迟迟得不到onLocationChanged的回调。我测试了安卓5,6, 7的设备,其中两个android5.1.1的设备一直都获取不到location,这就导致该定位无法在此设备上使用。查了各种网站,发现有两个网友遇到了同样的问题,但是取没有解决:https://segmentfault.com/q/1010000004477439/a-1020000006144410。

但是有一个奇怪的现象,就是我在android5.1.1的设备上测试的时候,偶尔是可以得到一次location的,但这个几率极低。网上有说需要等待一段时间,但是我等了个把小时都不行。

另外我也试了google的FusedLocationProviderClient方法,也是堵塞在requestLocationUpdates,实在是郁闷。由于我做的是一个海外的项目,所以什么百度API,腾讯API就不用想了。

这里贴出来也是希望大神们看到之后能够指正,并希望能帮忙解决上面这个问题,大家共同进步。


你可能感兴趣的:(Android开发)