首页 文章

我们可以将android.app.Service作为生命周期感知能力

提问于
浏览
1

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

现在如何让 android service 了解生命周期?到目前为止,我可以看到我们可以创建一个扩展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
    }

}

我这里有几个问题

  • 我如何观察ON_BIND和ON_UNBIND事件 . 因为我想减少我的服务代码 .

  • 我做错了什么,我们可以释放服务的使用生命周期arch

请帮我 .

谢谢

2 回答

  • 1

    来自源代码LifecycleServiceServiceLifecycleDispatcher

    我认为

    onCreate()是ON_CREATE事件

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

    onDestroy()是ON_STOP和ON_DESTROY事件

  • 1

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

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

相关问题