1. Handler放置在MainThread(UI)線程中
示例代碼
public class MainActivity extends Activity {
private final static int CHANGE = 1;
private static TextView textView;
private static Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case CHANGE :
textView.setText(msg.obj + "");
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.hello);
new Thread() {
public void run() {
for(int i=0;i<100;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = new Message();
msg.what = MainActivity.CHANGE;
msg.obj = i;
MainActivity.handler.sendMessage(msg);
}
}
}.start();
}
}
2. 將Handler綁定到另外一個線程(非MainThread線程)
示例代碼
public class MainActivity extends Activity {
private final static int CHANGE = 1;
private static TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.hello);
//生成一個HandlerThread對象,實現了使用Looper來處理消息隊列的功能,
//這個類由Android應用程序框架提供
HandlerThread handlerThread = new HandlerThread("handler_thread");
//在使用HandlerThread的getLooper()方法之前,必須先調用該類的start();
handlerThread.start();
MyHandler myHandler = new MyHandler(handlerThread.getLooper());
Message msg = myHandler.obtainMessage();
//將msg發送到目標對象,所謂的目標對象,就是生成該msg對象的handler對象
Bundle b = new Bundle();
b.putInt("age", 20);
b.putString("name", "Jhon");
msg.setData(b);
msg.sendToTarget();
}
class MyHandler extends Handler{
public MyHandler(){
super();
}
public MyHandler(Looper looper){
super(looper);
}
public void handleMessage(Message msg){
printCurrentThreadInfo();
Log.d("bing", "name-->" + msg.getData().getString("name"));
Log.d("bing", "age-->" + msg.getData().getInt("age"));
//tv.setText((String)msg.getData().getString("name")); //Error!
//這裏因爲與handlerThread同處在一個線程中,而不是在MainThread中
//因此無法在這裏更新UI!!
}
}
}
注意:這樣使用的話,可以將主線程的數據傳遞給另外一個線程,讓Handler進行處理。比如傳遞信息到服務器。