android app Service使用LiveData

Service 使用liveData

背景知识

数据绑定的方法如下

    @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        assertMainThread("observe");
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }

在Service中如何传递参数 LifecycleOwner 是个问题。
查阅后一种方法是手动实现LifecycleOwner 接口

public class MyService  extends Service implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

在这里有一个更方便的实现方法

  • androidx.lifecycle.LifecycleService
import androidx.lifecycle.LifecycleService;
public class MyService extends  LifecycleService {

}

具体使用如下所示

 import androidx.lifecycle.LifecycleService;
public class MyService extends  LifecycleService {

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		wakeUp().observe( this::getLifecycle, wakeUpOrSleep ->{
			if(wakeUpOrSleep) {
			
			onWakeUp();
			
			} else {
			
				onWaitingWakeUp();
				
			}
		});
		return START_STICKY;
	}
	    /**
     * 唤醒和休眠变化
     * @return
     */
    public LiveData<Boolean> wakeUp() {
        return mLiveWakeup;
    }
}

总结

LiveData的更简单完善的实现
LifecycleService 是个好类

你可能感兴趣的:(android,问题解决,java,android,android,studio)