weijunfeng
9/2/2019 - 9:47 AM

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

Android开发使用LocationManager实现定位服务
2018年04月25日 17:35:31 jiuyuefenglove 阅读数 6630更多
分类专栏: Android开发
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/jiuyuefenglove/article/details/80082076
做项目需要获取经纬度信息,学习了下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<String> 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<String> 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获取当前位置Location的两种方式
2019.01.22 09:51:36
字数225
阅读981
1.Android自带的api中有获取Location的方法
逻辑如下:
1.先优先取得GPS和NetWork的提供的位置情报
2.如果取不到,先获取PASSIVE的情报(其他应用的获取的Location),然后监听GPS
3.GPS有返回之后,通过Listener将情报信息再次返回

代码如下:

@EBean(scope = EBean.Scope.Singleton)
public class LocationProvider implements LocationListener {

    public interface LocationGetListener {
        void getLocationInfo(Location location);
    }

    @RootContext
    Context mContext;
    LocationManager mLocationManager;
    LocationGetListener mListener;

    @AfterInject
    void initProvider() {
           mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    }

    @SuppressLint("MissingPermission")
    public void getBestLocation(LocationGetListener listener) {
        mListener = listener;
        Location location;
        Criteria criteria = new Criteria();

        String provider = mLocationManager.getBestProvider(criteria, true);
        if (TextUtils.isEmpty(provider)) {
            location = getNetWorkLocation(mContext);
        } else {
            location = mLocationManager.getLastKnownLocation(provider);
        }
        if (location == null) {
            // 一旦、既存の位置情報を使用する。GPSで取得したあとで、情報を更新する
            provider = LocationManager.PASSIVE_PROVIDER;
            location = mLocationManager.getLastKnownLocation(provider);
            if (mListener != null) {
                mListener.getLocationInfo(location);
            }

            mLocationManager.requestLocationUpdates(provider, 60000, 1, this);
        } else if (mListener != null) {
            mListener.getLocationInfo(location);
        }
    }

    @SuppressLint("MissingPermission")
    public Location getNetWorkLocation(Context context) {
        Location location = null;

        if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

            location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        return location;
    }

    public void unregisterLocationUpdaterListener() {
        mLocationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        LogUtils.v("location : onLocationChanged");
        if (mListener != null) {
            mListener.getLocationInfo(location);
        }
        unregisterLocationUpdaterListener();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        LogUtils.v("location : " + provider + " onStatusChanged. status = " + status);
    }

    @Override
    public void onProviderEnabled(String provider) {
        LogUtils.v("location : " + provider + " onProviderEnabled");
    }

    @Override
    public void onProviderDisabled(String provider) {
        LogUtils.v("location : " + provider + " onProviderDisabled");
    }
}

上面的代码有一个需要注意点:如果是新的设备,没有安装任何获取location的app,那么使用这段代码如果在没有GPS和网络的情况下,使用PASSIVE方式是获取不到地址的,location是 null,这个时候就需要根据项目情况来设置默认地址。

如果使用Google 自带的Api也可以实现获取Location的方式
在gradle中导入依赖com.google.android.gms:play-services-location,java代码如下

public class GoogleMapManager {

    public static final int UPDATE_INTERVAL = 5000;
    public static final int FASTEST_UPDATE_INTNERVAL = 2000;

    private static GoogleMapManager googleMapManager;
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private LatLng myLocation;
    private Context mContext;

    private GoogleApiLinkListener mApiLinkListener;

    public interface GoogleApiLinkListener {
        void onConnected(@Nullable Bundle bundle);

        void onConnectionFailed(@NonNull ConnectionResult connectionResult);
    }

//注意这个地方使用aplication的 context,防止内存泄漏
    private GoogleMapManager(Context context) {
        this.mContext = context;
    }

    public GoogleApiClient getGoogleApiClient() {
        return mGoogleApiClient;
    }

    public static GoogleMapManager getGoogleApiManager(Context context) {
        if (googleMapManager == null) {
            googleMapManager = new GoogleMapManager(context);
        }
        return googleMapManager;
    }

    public GoogleMapManager initGoogleApiClient(GoogleApiLinkListener apiLinkListener) {
        this.mApiLinkListener = apiLinkListener;
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(@Nullable Bundle bundle) {
                            if (mApiLinkListener == null) {
                                return;
                            }
                            mApiLinkListener.onConnected(bundle);
                        }

                        @Override
                        public void onConnectionSuspended(int i) {

                        }
                    })
                    .addOnConnectionFailedListener(connectionResult -> {
                        if (mApiLinkListener == null) {
                            return;
                        }
                        mApiLinkListener.onConnectionFailed(connectionResult);
                    })
                    .addApi(LocationServices.API)
                    .build();
        }

        return googleMapManager;
    }

    public GoogleMapManager initGoogleLocationRequest() {
        if (mLocationRequest == null) {
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(UPDATE_INTERVAL)
                    .setFastestInterval(FASTEST_UPDATE_INTNERVAL);
        }

        return googleMapManager;
    }

// 该方法为获取location
    public LatLng getMyLocation() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, 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;
        } else {
// 这个地方不能直接获取location
// Task task = mFusedLocationProviderClient.getLastLocation();
// location = (Location) task.getResult();
// 参考链接:https://teamtreehouse.com/community/i-wanted-to-make-the-weather-app-detect-your-location
            LocationServices.getFusedLocationProviderClient(mContext)
                    .getLastLocation()
                    .addOnSuccessListener(location -> {
                        if (location != null) {
                            myLocation = new LatLng(location.getLatitude(), location.getLongitude());
                        }
                    });
        }

        return myLocation;
    }

    public void resetGoogleApiLinkListener() {
        mApiLinkListener = null;
    }

}