Android线程初窥(一)

1.简单线程Thread的使用

final Handler handler = new Handler(){
    public void handleMessage(Message msg) {
        //UI线程获得返回的消息
        //执行程序
        };
    };

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        //执行代码
        //向UI线程发送消息
        Message msg = Message.obtain();
        handler.sendMessage(msg);
    }
});

2.Looper的使用

public class LooperThread extends Thread{

    private Handler mHandler;
    private List<LooperObj> list = new ArrayList<LooperObj>();

    @Override
    public void run() {
        Looper.prepare();
        //必须先prepare()后才能获取Hander的实例
        mHandler = new Handler(){
            public void handleMessage(Message msg) {
                //处理收到的消息
            };
        };
        //线程循环处理消息开始
        Looper.loop();
    }
    void sendMessage(){
        if(mHandler == null){
            return;
        }
        //发送消息
        Message msg = Message.obtain();
        mHandler.sendMessage(msg);
    }

你可能感兴趣的:(线程,android)