1.简介:
LiveData 是一种可观察的数据存储器类。与常规的可观察类不同,LiveData 具有生命周期感知能力,意指它遵循其他应用组件(如 Activity、Fragment 或 Service)的生命周期。这种感知能力可确保 LiveData 仅更新处于活跃生命周期状态的应用组件观察者。
如果观察者(由 Observer 类表示)的生命周期处于 STARTED 或 RESUMED 状态,则 LiveData 会认为该观察者处于活跃状态。LiveData 只会将更新通知给活跃的观察者。为观察 LiveData 对象而注册的非活跃观察者不会收到更改通知。您可以注册与实现 LifecycleOwner 接口的对象配对的观察者。有了这种关系,当相应的 Lifecycle 对象的状态变为 DESTROYED 时,便可移除此观察者。这对于 Activity 和 Fragment 特别有用,因为它们可以放心地观察 LiveData 对象而不必担心泄露(当 Activity 和 Fragment 的生命周期被销毁时,系统会立即退订它们)。
2.创建一个ViewModel
/**
* @author: njb
* @date: 2020/8/24 0024 23:02
* @desc:
*/
public class TimerLiveDataViewModel extends ViewModel {
// 不能传入Context 和含有不能传入Context引用对象,会造成内存泄漏
private MutableLiveData<Integer> currentSecondLiveData;
private int currentSecond;
Timer timer;
public MutableLiveData<Integer> getCurrentSecond() {
if (currentSecondLiveData == null) {
currentSecondLiveData = new MutableLiveData<>();
}
return currentSecondLiveData;
}
public void startTiming() {
if (timer == null) {
currentSecond = 0;
timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
currentSecond++;
currentSecondLiveData.postValue(currentSecond);
}
};
timer.schedule(timerTask, 1000, 1000);//延迟3秒执行
}
}
/**
* 由于屏幕旋转导致的Activity重建,该方法不会被调用
* 只有ViewModel已经没有任何Activity与之有关联,系统则会调用该方法,你可以在此清理资源
*/
@Override
protected void onCleared() {
super.onCleared();
timer.cancel();
}
}
3.MainActivity代码:
public class MainActivity extends AppCompatActivity {
private TextView tvTime, tvRestart;
private MutableLiveData<Integer> liveData;
private TimerLiveDataViewModel timerLiveDataViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initLiveData();
}
private void initView() {
tvTime = findViewById(R.id.tv_time);
tvRestart = findViewById(R.id.tv_restart);
}
private void initLiveData() {
//得到ViewModel中LiveData
timerLiveDataViewModel = new ViewModelProvider(this).get(TimerLiveDataViewModel.class);
liveData = (MutableLiveData<Integer>) timerLiveDataViewModel.getCurrentSecond();
//通过LiveData.Observe()观察ViewModel中数据的变化
liveData.observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer second) {
tvTime.setText("Time : " + second);
}
});
//重置计时器
tvRestart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//完成ViewModel中数据的更新
liveData.setValue(0);//setValue()只能在主线程中调用
}
});
//计时开始
timerLiveDataViewModel.startTiming();
}
}
4.布局文件activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TiMER"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv_restart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/tv_time"
android:text="重新计时"
android:textSize="20sp"
android:layout_marginTop="20dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:visibility="visible"/>
</androidx.constraintlayout.widget.ConstraintLayout>
5.运行截图如下: