我们可以将android.app.Service作为生命周期意识的能力

时间:2018-05-09 19:19:20

标签: android android-lifecycle android-architecture-components

我从新的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
    }

}

我这里的问题很少

  1. 我如何观察ON_BIND和ON_UNBIND事件。因为我也希望减少我的服务代码。
  2. 我做错了什么,我们可以发布服务的使用生命周期arch
  3. 请帮帮我。

    由于

2 个答案:

答案 0 :(得分:3)

从源代码 LifecycleServiceServiceLifecycleDispatcher

我认为

onCreate()是ON_CREATE事件

onBind(),onStart()& onStartCommand()都是ON_START事件

onDestroy()是ON_STOP和ON_DESTROY事件

答案 1 :(得分:1)

Service类实际上只有两个生命周期:ON_CREATEON_DESTROYService中基于活页夹的回调不是生命周期回调,因此无法通过LifecycleObserver直接观察到它们。

感谢@vivart挖掘代码。他是正确的:当发生绑定时,会发送ON_START。但是,unbind没有生命周期事件,因此您的服务需要覆盖这些方法以将它们作为事件处理。