我从新的 Android 架构组件中得到的是,如果我们让组件生命周期感知,那么 LifecycleObserver 将根据 Activity 生命周期对事件使用react。这减少了我们在 onCreate、onStop 或 onStart 等 Activity 或 fragment 生命周期方法中编写的大量样板代码。
现在如何使 android 服务 具有生命周期感知能力? 到目前为止,我可以看到我们可以创建一个范围为 android.arch.lifecycle.LifecycleService 的服务。但是,我在观察时看不到任何与绑定(bind)和解除绑定(bind)相关的事件。
代码 fragment
// 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
}
}
我有几个问题
- 我如何观察 ON_BIND 和 ON_UNBIND 事件。因为我也想减少我的服务代码。
- 我做错了什么吗,我们可以发布服务的使用生命周期架构
最佳答案
来自源代码 LifecycleService和 ServiceLifecycleDispatcher
我觉得
onCreate()
是ON_CREATE
事件,onBind()
,onStart()
&onStartCommand()
都是ON_START
事件,onDestroy()
是ON_STOP
和ON_DESTROY
事件。
关于android - 我们可以将 android.app.Service 作为生命周期感知组件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50260616/