Service或自定義物件使用LiveData

zhuxingchong發表於2020-11-23

一,LiveData繫結AppCompatActivity或Fragment使用

有些情況我們需要在activity或service或其他物件上繫結使用。

正常情況下使用,this是Activity帶有生命週期該activity實現LifecycleOwner

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner
mTestViewModel = ViewModelProviders.of(this, new TestViewModel.Factory(mkey)).get(TestViewModel.class);
MutableLiveData<String> nameEvent = mTestViewModel.getNameEvent();
nameEvent.observe(this, new Observer<String>() {
    @Override
    public void onChanged(@Nullable String s) {
        Log.i(TAG, "onChanged: s = " + s);
    }
});

二,以下是在Service上使用LiveData例子

1.在需要監聽的物件上實現LifecycleOwner介面

實現生命週期管理物件返回LifecycleRegistry生命週期管理器

@Override
public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}

2.LifecycleRegistry物件在需要生命週期管理的地方標註(例如Service裡面的

onCreate,onStart,onBind,onUnbind,onStartCommand,onDestroy)如果是其他物件可以根據需求對應狀態。

3.新增監聽

final Observer<String> statusObserver = new Observer<String>() {
    @Override
    public void onChanged(@Nullable final String newName) {
        Log.d("PackageViewModel", TAG+" onChanged: " + newName);
    }
};

PackageViewModel.getsInstance().getStatus().observe(this, statusObserver);

完整程式碼:

public class PackageViewModel extends ViewModel {
    private MutableLiveData<String> status = new MutableLiveData<>();

    private static volatile PackageViewModel sInstance;
    private PackageViewModel(){

    }

    public static PackageViewModel getsInstance() {
        if(sInstance == null){
            synchronized (PackageViewModel.class){
                sInstance = new PackageViewModel();
            }
        }
        return sInstance;
    }

    public MutableLiveData<String> getStatus() {
        return status;
    }
}
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
import androidx.lifecycle.Observer;

public class MyService  extends Service implements LifecycleOwner {

    private final String TAG = getClass().getSimpleName();
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    @Override
    public void onCreate() {
        super.onCreate();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        initLiveDataObserver();
    }

    private void initLiveDataObserver() {
        final Observer<String> statusObserver = new Observer<String>() {
            @Override
            public void onChanged(@Nullable final String newName) {
                Log.d(TAG, " onChanged: " + newName);
            }
        };
        PackageViewModel.getsInstance().getStatus().observe(this, statusObserver);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
        PackageViewModel.getsInstance().getStatus().removeObservers(this);
        super.onDestroy();
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

非同步傳送訊息

PackageViewModel.getsInstance().getStatus().postValue(“測試");

 

相關文章