美文网首页Android开发进阶经验分享
Android获取当前位置Location的两种方式

Android获取当前位置Location的两种方式

作者: FreedApe | 来源:发表于2019-01-22 09:51 被阅读0次

    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,这个时候就需要根据项目情况来设置默认地址。

    1. 如果使用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;
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:Android获取当前位置Location的两种方式

        本文链接:https://www.haomeiwen.com/subject/vlakjqtx.html