【Android】HandleThread后台数据处理

时间:2021-06-14 18:28:55

Android HandlerThread 完全解析(张鸿洋)

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

private TextView textView;

private HandlerThread mMsgThread;
private Handler mMsgHandler;
private boolean isUpdateInfo;

private static final int MSG_UPDATE_INFO = 0x110;

private Handler mHandler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = (TextView)findViewById(R.id.textView);
initBackThread();
}

@Override
protected void onResume()
{
super.onResume();
//开始查询
isUpdateInfo = true;
mMsgHandler.sendEmptyMessage(MSG_UPDATE_INFO);
}

@Override
protected void onPause()
{
super.onPause();
//停止查询
isUpdateInfo = false;
mMsgHandler.removeMessages(MSG_UPDATE_INFO);
}

private void initBackThread(){
mMsgThread = new HandlerThread("check-message-coming");
mMsgThread.start();
mMsgHandler = new Handler( mMsgThread.getLooper()){
@Override
public void handleMessage(Message msg){
checkForUpdate();
if ( isUpdateInfo ){
mMsgHandler.sendEmptyMessageDelayed( MSG_UPDATE_INFO, 1000);
}
}
};
}

private void checkForUpdate(){
try{
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
String result = "实时更新中,指数:<font color='red'>%d</font>";
result = String.format(result, (int) (Math.random() * 3000 + 1000));
textView.setText(Html.fromHtml(result));
}
});
}catch (InterruptedException e){
e.printStackTrace();
}

}

@Override
protected void onDestroy()
{
super.onDestroy();
//释放资源
mMsgThread.quit();
}

}