Android獲取當(dāng)前位置Location的兩種方式

1.Android自帶的api中有獲取Location的方法

邏輯如下:
1.先優(yōu)先取得GPS和NetWork的提供的位置情報(bào)
2.如果取不到,先獲取PASSIVE的情報(bào)(其他應(yīng)用的獲取的Location),然后監(jiān)聽GPS
3.GPS有返回之后,通過(guò)Listener將情報(bào)信息再次返回

代碼如下:

@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) {
            // 一旦、既存の位置情報(bào)を使用する。GPSで取得したあとで、情報(bào)を更新する
            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");
    }
}

上面的代碼有一個(gè)需要注意點(diǎn):如果是新的設(shè)備,沒有安裝任何獲取location的app,那么使用這段代碼如果在沒有GPS和網(wǎng)絡(luò)的情況下,使用PASSIVE方式是獲取不到地址的,location是 null,這個(gè)時(shí)候就需要根據(jù)項(xiàng)目情況來(lái)設(shè)置默認(rèn)地址。

  1. 如果使用Google 自帶的Api也可以實(shí)現(xiàn)獲取Location的方式

在gradle中導(dǎo)入依賴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);
    }

//注意這個(gè)地方使用aplication的 context,防止內(nèi)存泄漏
    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 {
// 這個(gè)地方不能直接獲取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;
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom閱讀 3,214評(píng)論 0 3
  • 一、簡(jiǎn)歷準(zhǔn)備 1、個(gè)人技能 (1)自定義控件、UI設(shè)計(jì)、常用動(dòng)畫特效 自定義控件 ①為什么要自定義控件? Andr...
    lucas777閱讀 5,389評(píng)論 2 54
  • 小晴寒九天 北雁翩躚 殘枝臘葉不堪憐 今春我慕可再還? 仍是單戀 無(wú)意久探看 山花爛漫 待君從中步轉(zhuǎn)蓮 抬淚眼 期...
    鎏金夜叉閱讀 189評(píng)論 0 0
  • 我近期的目標(biāo)是讓兒子快樂(lè)學(xué)習(xí)、提高的學(xué)習(xí)熱情和書寫的認(rèn)真,提升學(xué)習(xí)成績(jī),各科成績(jī)達(dá)到95分,為小升初打下堅(jiān)實(shí)的基礎(chǔ)...
    歸韻閱讀 149評(píng)論 0 2
  • 圖片來(lái)自網(wǎng)絡(luò) 1/ 讀書時(shí)候,考試之前,很多人都是平時(shí)不努力,臨時(shí)抱佛腳的,確實(shí)連佛腳都抱不了了,就會(huì)偶爾有人抱著...
    拼出美麗閱讀 659評(píng)論 0 1

友情鏈接更多精彩內(nèi)容