【问题标题】:Can we make android.app.Service as lifecycle aware component我们可以将 android.app.Service 作为生命周期感知组件吗
【发布时间】:2019-11-21 17:27:57
【问题描述】:

我从新的 Android 架构组件中得到的只是,如果我们让组件生命周期感知,那么 LifecycleObserver 将根据活动生命周期对事件做出反应。这减少了我们在 onCreate、onStop 或 onStart 等活动或片段生命周期方法中编写的大量样板代码。

现在如何使 android 服务 具有生命周期感知能力? 到目前为止,我可以看到我们可以创建一个范围为 android.arch.lifecycle.LifecycleService 的服务。但是,我在观察时看不到任何与绑定和取消绑定相关的事件。

代码sn-ps

// 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


    【解决方案1】:

    来自源代码 LifecycleServiceServiceLifecycleDispatcher

    我觉得

    • onCreate()ON_CREATE 事件,

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

    • onDestroy()ON_STOPON_DESTROY 事件。

    【讨论】:

    • @vivart 链接失效
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多