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
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.
The Service
class really only has two lifecycle evens: ON_CREATE
and ON_DESTROY
. The binder based callbacks in the Service
are not lifecycle callbacks, so they cannot be observed directly via LifecycleObserver
.
Kudos to @vivart for digging into the code. He's correct: when bind happens, ON_START
is sent. However, there is not a life cycle event for unbind, so your service need to override those methods to handle them as events.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.