android线程开发中HandlerThread的使用

Home / Android MrLee 2015-4-21 3613

在Android开发中经常会使用到线程,一想到线程,很多同学就立即使用new Thread(){...}.start()这样的方式。这样如果在一个Activity中多次调用上面的代码,那么将创建多个匿名线程,程序运行的越久可能会越来越慢。因此,需要一个Handler来启动一个线程,以及删除一个线程,保证线程不会重复的创建 (有部分人可能用cachethreadpool来实现)。
1、创建Handler的一般方式 一般会使用Handler handler = new Handler(){...}创建。这样创建的handler是在主线程即UI线程下的Handler,即这个Handler是与UI线程下的默认Looper绑定的。Looper是用于实现消息队列和消息循环机制的。 因此,如果是默认创建Handler那么如果线程是做一些耗时操作如网络获取数据等操作,这样创建Handler是不行的。
2、使用HandlerThread HandlerThread实际上就一个Thread,只不过它比普通的Thread多了一个Looper。我们可以使用下面的例子创建Handler
HandlerThread thread = new HandlerThread("MyHandlerThread"); 
thread.start(); 
mHandler = new Handler(thread.getLooper()); 
mHandler.post(mBackgroundRunnable);
创建HandlerThread时要把它启动了,即调用start()方法。然后创建Handler时将HandlerThread中的looper对象传入。那么这个mHandler对象就是与HandlerThread这个线程绑定了(这时就不再是与UI线程绑定了,这样它处理耗时操作将不会阻塞UI)。 最后把实现耗时操作的线程post到mHandler的消息队列里面。注意的是,mBackgroundRunnable这个线程并没有启动,因为没有调用start()方法。
3、完整的angrycode
public class MainActivity extends Activity implements OnClickListener {
	public static final String TAG = "MainActivity";
	private Handler mHandler;
	private boolean mRunning = false;
	private Button mBtn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		HandlerThread thread = new HandlerThread("MyHandlerThread");
		thread.start();// 创建一个HandlerThread并启动它
		mHandler = new Handler(thread.getLooper());// 使用HandlerThread的looper对象创建Handler,如果使用默认的构造方法,很有可能阻塞UI线程
		mHandler.post(mBackgroundRunnable);// 将线程post到Handler中
		mBtn = (Button) findViewById(R.id.button);
		mBtn.setOnClickListener(this);
	}
	@Override
	protected void onResume() {
		super.onResume();
		mRunning = true;
	}
	@Override
	protected void onStop() {
		super.onStop();
		mRunning = false;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	// 实现耗时操作的线程
	Runnable mBackgroundRunnable = new Runnable() {
		@Override
		public void run() {
			// ----------模拟耗时的操作,开始---------------
			while (mRunning) {
				Log.i(TAG, "thread running!");
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			// ----------模拟耗时的操作,结束---------------
		}
	};
	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 销毁线程
		mHandler.removeCallbacks(mBackgroundRunnable);
	}
	@Override
	public void onClick(View v) {
		Toast.makeText(getApplication(), "click the button!!!",
				Toast.LENGTH_SHORT).show();
	}
}
4、线程销毁 用上面的方式来创建线程,在销毁时就可以使用 mHandler.removeCallbacks(mBackgroundRunnable); 销毁一个线程,这样就可以避免在多次进入同一个Activity时创建多个同时运行着的线程。

本文链接:https://www.it72.com/2275.htm

推荐阅读
最新回复 (0)
返回