preface

While studying Jetpack recently, Lifecycle optimization was needed for the map aspect of the project.

The role of the Lifecycle

Lifecycle is a Lifecycle aware component that addresses Lifecycle issues in activities and fragments.

Basic use of Lifecycle

Import the dependency library

implementation "Androidx. Lifecycle: lifecycle - runtime: 2.1.0." "
Copy the code

Second, activities inherit AppCompatActivity or implement LifecycleOwner interface themselves

Since BaseActivity is an inherited AppCompatActivity in the project, the LifecycleOwner interface is not implemented here.

Create AMapLocationListener

  1. Implement LifecycleObserver
public class AMapLocationListener implements LifecycleObserver {
    
}
Copy the code
  1. make@OnLifecycleEventAnnotations to indicate the life cycle of a featureLifecycle.Event.ON_CREATEThe correspondingonCreate
 @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void createLocation(){
        initLocation();
        startLocation();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void destroyLocal(){
        destroyLocation();
    }
Copy the code
  1. Finally, use it in your Activity
AMapLocationListener = new AMapLocationListener(); getLifecycle().addObserver(aMapLocationListener);Copy the code

Here’s the full code

AMapLocationListener

public class AMapLocationListener implements LifecycleObserver { private AMapLocationClient locationClient; // declare mLocationOption object private AMapLocationClientOption locationOption = null; private LatLng myLatlng; public LatLnggetMyLatlng() {
        return myLatlng;
    }

    private void setMyLatlng(LatLng myLatlng) {
        this.myLatlng = myLatlng;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void createLocation(){
        initLocation();
        startLocation();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void destroyLocal(){
        destroyLocation();
    }

    private void initLocation() {/ / initializes the client locationClient = new AMapLocationClient (FPVDemoApplication. GetContext ()); locationOption = getDefaultOption(); / / set the position parameter locationClient. SetLocationOption (locationOption); / / set positioning monitoring locationClient setLocationListener (locationListener); } /** * The default positioning parameter */ private AMapLocationClientOptiongetDefaultOption() { AMapLocationClientOption mOption = new AMapLocationClientOption(); mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); // Optional, set the location mode, the options are high precision, device only, network only. Default to high precision mode moption.setgpsFirst (true); // This parameter is optional. It takes effect only in high-precision mode. Moption. setHttpTimeOut(30000) is disabled by default. // Optional, set the network request timeout period. The default value is 30 seconds. Invalid in device-only mode moption. setInterval(5 * 1000); // Optional, set the positioning interval. Default is 2 seconds moption.setNeedAddress (true); // Optional, set whether to return the inverse geographic address information. The default istrue
        mOption.setOnceLocation(false); // This parameter is optional. The default isfalse
        mOption.setOnceLocationLatest(false); // Optional, set whether to wait for wifi refresh. The default value is falsetrue, will automatically into a single location for positioning. Don't use the AMapLocationClientOption setLocationProtocol (AMapLocationClientOption. AMapLocationProtocol. HTTP); // Optional, set the network request protocol. The value can be HTTP or HTTPS. Default is HTTP moption.setSensorenable (false); // Optional, set whether to use the sensor. The default isfalse
        mOption.setWifiScan(true); // Optional, set whether to enable WIFI scanning. The default istrueIf it is set tofalseWill stop at the same time take the initiative to refresh, refresh after stop depends entirely on the system, locating position possible error mOption. SetLocationCacheEnable (true); // Optional: Whether to use cache location. The default value is cache locationtrue//mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT); // Optional, set the language of the inverse geographic information. The default value is default language (select language based on the location).returnmOption; } / positioning monitoring * / * * * com. Amap. API. The location. The AMapLocationListener locationListener = new com. Amap. API. The location.AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if(null ! = location) { StringBuffer sb = new StringBuffer(); If errCode is 0, the location succeeds. If errCode is 0, the location fails. For details, see the description of locating error codes on the official websiteif (location.getErrorCode() == 0) {
                    double lat = location.getLatitude();
                    double lon = location.getLongitude();
                    myLatlng = new LatLng(lat,lon);
                    setMyLatlng(myLatlng);
                } else{// Failed to locate sb. Append ("Location failure" + "\n");
                    sb.append(Error code: + location.getErrorCode() + "\n");
                    sb.append(Error message: + location.getErrorInfo() + "\n");
                    sb.append("Misdescription :" + location.getLocationDetail() + "\n"); }}}}; private voidstartLocation() {/ / start positioning locationClient startLocation (); } /** * @author hongming.wang * @since 2.8.0 */ private voiddestroyLocation() {
        if(null ! = locationClient) {/** * if AMapLocationClient is instantiated in the current Activity, * in the Activity onDestroy must perform AMapLocationClient onDestroy * / / / locationClient disableBackgroundLocation (true); locationClient.stopLocation(); locationClient.unRegisterLocationListener(locationListener); locationClient.onDestroy(); locationClient = null; locationOption = null; Public void moveTolocation(AMap AMap) {public void moveTolocation(AMap AMap) {if(aMap ! = null && myLatlng ! = null) {/ / move the map to the anchor point aMap. MoveCamera (CameraUpdateFactory. ChangeLatLng (myLatlng)); }}}Copy the code

The Activity is used in

AMapLocationListener = new AMapLocationListener(); getLifecycle().addObserver(aMapLocationListener); btnLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { aMapLocationListener.moveTolocation(amap); }});Copy the code

The subsequent preparation continues to optimize, plus zoom out or map mode switching functions