使用Android的LiveData,需要在gradle添加引用:
compile "android.arch.lifecycle:runtime:1.0.0"
compile "android.arch.lifecycle:extensions:1.0.0"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
本文是基于三个引用的新版Version 1.0.0写的代码,我在使用其他版本比如Version 1.0.0alpha4,代码运行报错。如果遇到这种情况,请自行添加最新的版本引用。在1.0.0中,个别类和方法已经被Google Android官方废弃或者调整,比如LifecycleActivity已经过时,Android官方已经推荐开发者使用AppCompatActivity替换LifecycleActivity。一些关于Lifecycle的内容和技术,已经被Android官方写入AppCompatActivity,望周知。
package zhangphil.app;
import android.arch.lifecycle.MutableLiveData;
import android.util.Log;
public class MyData extends MutableLiveData {
private final String TAG = "LiveData";
private int count = 0;
private boolean RUN = true;
private LongTimeWork mThread = new LongTimeWork();
public MyData() {
mThread.start();
}
@Override
protected void onActive() {
super.onActive();
Log.d(TAG, "onActive");
RUN = true;
mThread.interrupt();
}
@Override
protected void onInactive() {
super.onInactive();
Log.d(TAG, "onInactive");
RUN = false;
}
private class LongTimeWork extends Thread {
@Override
public void run() {
while (true) {
try {
if (!RUN) {
Thread.sleep(Long.MAX_VALUE);
}
} catch (Exception e) {
e.printStackTrace();
}
count++;
postValue(String.valueOf(count));
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
package zhangphil.app;
import android.arch.lifecycle.Observer;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyObserver observer = new MyObserver();
MyData data = new MyData();
data.observe(this, observer);
}
private class MyObserver implements Observer {
@Override
public void onChanged(@Nullable String o) {
Toast.makeText(getApplicationContext(),String.valueOf(o),Toast.LENGTH_SHORT).show();
}
}
}