我从新的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
}
}
我在这里有几个问题
请帮助我。
谢谢
从源代码LifecycleService和ServiceLifecycleDispatcher
我认为
[onCreate()
是ON_CREATE
事件,
[onBind()
,onStart()
和onStartCommand()
都是ON_START
事件,
[onDestroy()
是ON_STOP
和ON_DESTROY
事件。
Service
类实际上只有两个生命周期偶数:ON_CREATE
和ON_DESTROY
。 Service
中基于活页夹的回调不是生命周期回调,因此无法直接通过LifecycleObserver
进行观察。
感谢@vivart深入探讨了代码。他是正确的:绑定发生时,会发送ON_START
。但是,没有取消绑定的生命周期事件,因此您的服务需要重写这些方法以将其作为事件处理。