我从新的Android架构组件获得的是,如果我们让组件生命周期知道,那么LifecycleObserver将根据活动生命周期对事件作出反应。这减少了我们在onCreate,onStop或onStart等活动或片段生命周期方法中编写的大量样板代码。
现在如何让 android服务识别生命周期? 到目前为止,我可以看到我们可以创建一个扩展android.arch.lifecycle.LifecycleService的服务。但是,在观察时,我看不到与绑定和解除绑定相关的任何事件。
代码段
// 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
}
}
我这里的问题很少
请帮帮我。
由于
答案 0 :(得分:3)
从源代码 LifecycleService和ServiceLifecycleDispatcher
我认为
onCreate()是ON_CREATE事件
onBind(),onStart()& onStartCommand()都是ON_START事件
onDestroy()是ON_STOP和ON_DESTROY事件
答案 1 :(得分:1)
Service
类实际上只有两个生命周期:ON_CREATE
和ON_DESTROY
。 Service
中基于活页夹的回调不是生命周期回调,因此无法通过LifecycleObserver
直接观察到它们。
感谢@vivart挖掘代码。他是正确的:当发生绑定时,会发送ON_START
。但是,unbind没有生命周期事件,因此您的服务需要覆盖这些方法以将它们作为事件处理。