我们能否将android.app.Service做成生命周期感知组件

问题描述 投票:3回答:2

我从新的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. 我做错什么了,我们可以为服务发布使用生命周期拱门吗
android android-lifecycle android-architecture-components
2个回答
4
投票

从源代码LifecycleServiceServiceLifecycleDispatcher

我认为

  • [onCreate()ON_CREATE事件,

  • [onBind()onStart()onStartCommand()都是ON_START事件,

  • [onDestroy()ON_STOPON_DESTROY事件。


2
投票

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

感谢@vivart深入探讨了代码。他是正确的:绑定发生时,会发送ON_START。但是,没有取消绑定的生命周期事件,因此您的服务需要重写这些方法以将其作为事件处理。

© www.soinside.com 2019 - 2024. All rights reserved.