本文主要是介绍安卓HandlerThread使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
做程序员的好处就是,你永远都觉得你不会的太多。
言归正传,所谓HandlerThread,本质就是一个Thread,并在这个Thread的run方法中进行了Looper的相关操作.
下面是HandlerThread的run方法源码:
@Overridepublic void run() {mTid = Process.myTid();Looper.prepare();synchronized (this) {mLooper = Looper.myLooper();notifyAll();}Process.setThreadPriority(mPriority);onLooperPrepared();Looper.loop();mTid = -1;}
使用:
比如,我们要在子线程中每隔5秒拉取数据更新UI,我们可以在HandlerThread对应的Handler中进行数据拉取操作。
package com.example.yanruzhang.imagecache.handlerThread;import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;import com.example.yanruzhang.imagecache.R;import java.util.Random;/*** Created by yanru.zhang on 16/8/23.*/
public class HandlerThreadActivity extends Activity {private TextView textView;private HandlerThread handlerThread;private Handler threadHandler;private Handler mainHandler;private static final int UPDATE_UI = 1;private static final int GET_DATA = 2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_handler_thread);textView = (TextView) findViewById(R.id.tv);handlerThread = new HandlerThread("zyr thread");handlerThread.start();threadHandler = new Handler(handlerThread.getLooper(),new Handler.Callback() {private Random random = new Random();@Overridepublic boolean handleMessage(Message msg) {switch (msg.what){case GET_DATA://子线程做的事情Log.d("zyr",Thread.currentThread().getName());try {int i = random.nextInt();//得到结果给主线程更新uiMessage message = new Message();message.what = UPDATE_UI;Bundle bundle = new Bundle();bundle.putInt("i",i);message.setData(bundle);mainHandler.sendMessage(message);Thread.sleep(5000);//给ThreadHandler发消息再拉取数据threadHandler.sendEmptyMessage(GET_DATA);} catch (InterruptedException e) {e.printStackTrace();}break;}return true;}});mainHandler = new Handler(new Handler.Callback() {@Overridepublic boolean handleMessage(Message msg) {switch (msg.what){case UPDATE_UI:int i = msg.getData().getInt("i");textView.setText(i+"");break;}return true;}});}@Overrideprotected void onResume() {super.onResume();threadHandler.sendEmptyMessage(GET_DATA);}@Overrideprotected void onDestroy() {super.onDestroy();threadHandler.removeMessages(GET_DATA);handlerThread.quit();}
}
这篇关于安卓HandlerThread使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!