android - 我们可以将 android.app.Service 作为生命周期感知组件吗

标签 android android-lifecycle android-architecture-components

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

我有几个问题

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

最佳答案

来自源代码 LifecycleServiceServiceLifecycleDispatcher

我觉得

  • onCreate()ON_CREATE事件,

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

  • onDestroy()ON_STOPON_DESTROY 事件。

关于android - 我们可以将 android.app.Service 作为生命周期感知组件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50260616/

相关文章:

android - 大于运算符 (>) 未从数据库中给出正确的结果

java - 序列化性能和 Google Android

android - 如何将用户币添加到 Kotlin 中的现有币中?

android - ViewPager fragment 中的 onPause() 不起作用

android - RecyclerView 使用 Room 和 PagingListAdapter 向下滚动数据更新

java - 当我运行我的解析推送应用程序时,在 Parse.initialize(ctx, "***", "***") 中抛出 NullPointerException storage == null

android - 收到低内存警告,但我似乎没有泄漏内存

android - 检查导航图是否在 backstack 上

android - 如何确保 WorkManager 取消我的 Worker?