布局中添加一个按钮即可:
package com.cn.hpu.handlerthread; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends Activity { private static final int MESSAGE_TEST = 9; private Handler handler; private Looper looper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out .println("MAIN Thread ID = " + Thread.currentThread().getId()); // handler = new Handler(new InnerHandlerCallBack()); new WorkThread().start(); } public void sendMessage(View view) { handler = new Handler(looper,new InnerHandlerCallBack()); Message.obtain(handler, MESSAGE_TEST).sendToTarget(); } private class InnerHandlerCallBack implements Handler.Callback { @Override public boolean handleMessage(Message msg) { // TODO Auto-generated method stub System.out.println("Thread ID = " + Thread.currentThread().getId()); return false; } } private class WorkThread extends Thread { @Override public void run() { // TODO Auto-generated method stub Looper.prepare(); // handler = new Handler(new InnerHandlerCallBack()); handler = new Handler(Looper.getMainLooper(), new InnerHandlerCallBack()); Looper.loop(); } } }
MainActivity: public class MainActivity extends Activity { private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); HandlerThread handlerThread = new HandlerThread(""); handlerThread.start(); handler = new Handler(handlerThread.getLooper(),new InnerHandlerCallback()); } public void sendMessage(View view){ Message.obtain(handler).sendToTarget(); } private class InnerHandlerCallback implements Handler.Callback{ @Override public boolean handleMessage(Message msg) { // TODO Auto-generated method stub System.out.println(" InnerHandlerCallback Thread ID = " + Thread.currentThread().getId());; return false; } } }
简单的使用HandlerThread实例:
布局同上,
public class MainActivity extends Activity { private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); HandlerThread handlerThread = new HandlerThread(""); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); } public void sendMessage(View view){ handler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println("Thread ID = " + Thread.currentThread().getId()); } }); } }