Lifecycle is what?
Lifecycle is an Android Lifecycle management component. In Android, activities and fragments have their own Lifecycle. For Android development, the Lifecycle of the interface is very important. In Android development, the implementation of many functions need to be called in different life cycles of the corresponding operation, such as maps, positioning needs to start operation in onStart, stop operation in onStop; The player also needs to connect in onStart and break the connection in onStop. If we forget to release resources in onStop or onDestory, we can cause memory leaks.
To understand Lifecycle and traditional Lifecycle management more clearly, I have included sample code from Google to give you a better understanding of Lifecycles
Kotlin code:
internal class MyLocationListener(
private val context: Context,
private val callback: (Location) -> Unit
) {
fun start(a) {
// connect to system location service
}
fun stop(a) {
// disconnect from system location service}}class MyActivity : AppCompatActivity() {
private lateinit var myLocationListener: MyLocationListener
override fun onCreate(...). {
myLocationListener = MyLocationListener(this) { location ->
// update UI}}public override fun onStart(a) {
super.onStart()
myLocationListener.start()
// manage other components that need to respond
// to the activity lifecycle
}
public override fun onStop(a) {
super.onStop()
myLocationListener.stop()
// manage other components that need to respond
// to the activity lifecycle}}Copy the code
Java code:
class MyLocationListener {
public MyLocationListener(Context context, Callback callback) {
// ...
}
void start(a) {
// connect to system location service
}
void stop(a) {
// disconnect from system location service}}class MyActivity extends AppCompatActivity {
private MyLocationListener myLocationListener;
@Override
public void onCreate(...). {
myLocationListener = new MyLocationListener(this, (location) -> {
// update UI
});
}
@Override
public void onStart(a) {
super.onStart();
myLocationListener.start();
// manage other components that need to respond
// to the activity lifecycle
}
@Override
public void onStop(a) {
super.onStop();
myLocationListener.stop();
// manage other components that need to respond
// to the activity lifecycle}}Copy the code
This code is a standard example in Android development, so there is a lot of code in the various lifecycle methods, such as onStart () and onStop (), which makes them difficult to maintain.
Lifecycle is introduced
Lifecycle components include LifecycleOwner, LifecycleObserver. LifeCyclerObserver is the interface we need to implement for our life-cycle-aware class, which has no methods. In this class we annotate to indicate at what time in the LifeCycleOwner the function is executed. Classes that implement the LifecycleObserver interface can add annotations on methods to monitor the Lifecycle of the UI interface from their component to Lifecycle, and observers can be added by calling the addObserver () method of the Lifecycle class to pass an observer instance.
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void connectListener(a) {... }@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void disconnectListener(a) {... } } myLifecycleOwner.getLifecycle().addObserver(new MyObserver());
Copy the code
Don’t worry, there will be a full feature later to demonstrate using Lifecycle. Lifecycle.Event (Lifecycle.Event) was mentioned above in the OnLifecycleEvent annotation. For a better understanding I used an image from Google Documentation to illustrate
LifeCycleOwner is also an interface, and this interface has only one method, getLifeCycle. Used to indicate that its implementation class is a class with a life cycle. LifeCycleOwner interfaces are implemented for activities and fragments in the Support library after 26.0.1. So usually we don’t need to implement the LifecycleOwner ourselves, we just need to implement the lifecycleObserver.
How Lifecycle is used
Lifecycle will be used with an example of getting a location. First let’s create a BoundLocationManager class. Okay
public class BoundLocationManager {
public static void bindLocationListenerIn(LifecycleOwner lifecycleOwner, LocationListener listener, Context context) {
new BoundLocationListener(lifecycleOwner, listener, context);
}
@SuppressWarnings("MissingPermission")
static class BoundLocationListener implements LifecycleObserver {
private final Context mContext;
private LocationManager mLocationManager;
private final LocationListener mListener;
public BoundLocationListener(LifecycleOwner lifecycleOwner, LocationListener listener, Context context) {
mContext = context;
mListener = listener;
lifecycleOwner.getLifecycle().addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void addLocationListener(a) {
mLocationManager =
(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0.0, mListener);
Log.d("BoundLocationMgr"."Listener added");
// Force an update with the last location, if available.
Location lastLocation = mLocationManager.getLastKnownLocation(
LocationManager.GPS_PROVIDER);
if(lastLocation ! =null) { mListener.onLocationChanged(lastLocation); }}@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void removeLocationListener(a) {
if (mLocationManager == null) {
return;
}
mLocationManager.removeUpdates(mListener);
mLocationManager = null;
Log.d("BoundLocationMgr"."Listener removed"); }}}Copy the code
BoundLocationListener implements the LifecycleObserver interface, LifecycleOwner (which calls the Activity or fragment of BoundLocationManager),LocationListener(which is listening to locate changes), and Context (which is needed to initialize the location) are passed in the constructor.
The addLocationListener() method is annotated @onlifecycleEvent (Lifecycle.event.on_resume) to mean that addLocationListener() is only available at LifecycleOwner (i.e. Ac) The lifetime of the tivity or fragment is onResume().
Annotations are added to the removeLocationListener () method OnLifecycleEvent(Lifecycle.event.on_pause) means removeLocationListener () is only onPau for LifecycleOwner (i.e. Activity or fragment) Se ().
The BoundLocationListener class listens for an Activity or fragment’s lifecycle and automatically executes its lifecycle lock method.
One more thing to note: In BoundLocationListener constructor lifecycleOwner. GetLifecycle (). The addObserver (this), only add this code, BoundLocationListener checks the life cycle of its Activity or FragMeng.
So how should we use it in an Activity? It’s as simple as adding a line of code to your Activity or Fragmeng
private void bindLocationListener(a) {
BoundLocationManager.bindLocationListenerIn(this, mGpsListener, getApplicationContext());
}
Copy the code
Lifecycle will allow us to manage the Lifecycle of an Activity or fragment and will greatly simplify the code in that Activity or fragment. And we’re much less likely to have a memory leak. I’ll display the complete code from the Activity below
public class LocationActivity extends AppCompatActivity {
private static final int REQUEST_LOCATION_PERMISSION_CODE = 1;
private LocationListener mGpsListener = new MyLocationListener();
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
bindLocationListener();
} else {
Toast.makeText(this."This sample requires Location access", Toast.LENGTH_LONG).show(); }}private void bindLocationListener(a) {
BoundLocationManager.bindLocationListenerIn(this, mGpsListener, getApplicationContext());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_activity);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ! = PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this.new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_LOCATION_PERMISSION_CODE);
} else{ bindLocationListener(); }}private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
TextView textView = findViewById(R.id.location);
textView.setText(location.getLatitude() + "," + location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}@Override
public void onProviderEnabled(String provider) {
Toast.makeText(LocationActivity.this."Provider enabled: " + provider, Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {}}}Copy the code
The Activity layout file contains only one TextView, so the code is omitted.
How to customize LifecycleOwner?
Lifecycle Lifecycle is implemented for activities and fragments in the Support library after 26.0.1. What should Lifecycle be implemented for activities and fragments in the support library after 26.0.1? Customizinglifecycleowner is as simple as having your class implement the LifecycleOwner interface and add a few lines of code to its lifecycle.
public class MyActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry lifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.markState(Lifecycle.State.CREATED);
}
@Override
public void onStart(a) {
super.onStart();
lifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle(a) {
returnlifecycleRegistry; }}Copy the code
That’s how Lifecycle will be used. Lifecycle is very simple and I believe you will see that Lifecycle is pretty much understood. We will look at the use of ViewModel and LiveData and hopefully we can all move forward with that.