android中的Handler(2)
一、独立于主线程的Handler
HandlerThread是一个独立于主线程的线程,注意必须运行HandlerThread的start方法
通过Looper向HandlerThread中添加Handler,Handler于是就独立于主线程了
二、代码
package linys.handle;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
/**
*
* @Project: Android_HandlerThread
* @Desciption: 使用HandlerThread 使Handle中的Runnable独立于Main线程
* @Author: LinYiSong
* @Date: 2011-3-9~2011-3-9
*/
public class HandlerThreadlerDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("Main--->"+Thread.currentThread().getId());//通过比较Main和MyHandler的id说明线程独立
//创建一个HandlerThread,就是创建一个独立于Main线程的线程,但必须调用start
HandlerThread handlerThread=new HandlerThread("handle");
handlerThread.start();
//通过Looper向HandlerThread中添加Handler
MyHandler myHandler=new MyHandler(handlerThread.getLooper());
Message msg=myHandler.obtainMessage();
//利用Message中的arg1变量传递信息
// msg.arg1=1;
// msg.sendToTarget();//向拥有此Message中传递信息,此处是myHandler
//利用Message中的Bundle传递信息
/*
* Bundle可以认为是一个key值只能是String的Map
*/
Bundle bundle=new Bundle();
bundle.putString("username","linys");
bundle.putInt("password",123456);
msg.setData(bundle);
msg.sendToTarget();
}
class MyHandler extends Handler{
public MyHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// int arg1=msg.arg1;
// System.out.println("MyHandler--->"+arg1);
// System.out.println("MyHandler--->"+Thread.currentThread().getId());//验证线程独立
Bundle bundle=msg.getData();
System.out.println("username: "+bundle.getString("username")+" password: "+bundle.getInt("password"));
System.out.println("MyHandler--->"+Thread.currentThread().getId());
}
}
class MyRun implements Runnable{
@Override
public void run() {
System.out.println("MyRun--->"+Thread.currentThread().getId());
}
}
}