all I get from the new Android Architecture Components is, if we make the component lifecycle aware then depending on the activity lifecycle the LifecycleObserver will react to the events. That reduces a lot of boilerplate code that we write in onCreate,onStop or onStart etc. activity or fragment lifecycle methods.
Now how to make an android service a lifecycle aware? So far I can see is we can create a service that extent android.arch.lifecycle.LifecycleService. However, I can't see any event related to bind and unbind while I am observing.
Code snippets
// MY BOUNDED service
public class MyService extends LifecycleService
implements LocationManager.LocationListener{
private LocationManager mLocationManager;
@Override
public void onCreate() {
super.onCreate();
mLocationManager = LocationManager.getInstance(this, this);
mLocationManager.addLocationListener(this);
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
}
...
}
public class LocationManager implements LifecycleObserver{
public interface LocationListener {
void onLocationChanged(Location location);
}
private LocationManager(LifecycleOwner lifecycleOwner, Context context){
this.lifecycleOwner =lifecycleOwner;
this.lifecycleOwner.getLifecycle().addObserver(this);
this.context = context;
}
public static LocationAccessProcess getInstance(LifecycleOwner lifecycleOwner, Context context) {
// just accessiong the object using static method not single ton actually, so don't mind for now
return new LocationAccessProcess(lifecycleOwner, context);
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void startLocationUpdates() {
// start getting location updates and update listener
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void stopLocationUpdates() {
// stop location updates
}
}
I have few questions here
An Android activity goes through six major lifecycle stages or callbacks. These are: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() .
Lifecycle Awareness :Viewmodel is lifecycle aware. It is automatically cleared when the lifecycle they are observing gets permanently destroyed.
Android Activity Lifecycle is controlled by 7 methods of android.
From source code LifecycleService and ServiceLifecycleDispatcher
I think
onCreate()
is ON_CREATE
event,
onBind()
, onStart()
& onStartCommand()
all are ON_START
event,
onDestroy()
is ON_STOP
and ON_DESTROY
event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With