HandlerThread

package com.test.handerThread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
 * 在别的线程中创建Handler需要实例化一个Looper对象先,而HandlerThread提供了这个Looper对象(Looer.prepare(),Looer.loop(),)
 * 在UI线程中创建Handler,系统的框架会默认创建一个与之相关的Looper对象
 * 
 * @author Administrator
 *
 */
public class HandlerThreadDemoActivity extends Activity {
    private Handler mHandler;
    private MyHandlerThread myHandlerThread;
    private Button btn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn=(Button) findViewById(R.id.button1);
        System.out.println("oncreate current thread="+Thread.currentThread().getName());
        myHandlerThread=new MyHandlerThread("MyHandlerThread");
        myHandlerThread.start();//要开启线程哦
//        mHandler=new Handler(myHandlerThread.getLooper()){
//        	@Override
//        	public void handleMessage(Message msg) {
//        		 System.out.println("current thread="+Thread.currentThread().getName());
//        		super.handleMessage(msg);
//        	}
//        };
        
        mHandler=new Handler(myHandlerThread.getLooper(), myHandlerThread);
        
        
        btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mHandler.sendEmptyMessage(0);
				
			}
		});
    }
    
    
    class MyHandlerThread extends HandlerThread implements Callback{

		public MyHandlerThread(String name) {
			super(name);
			
		}

		@Override
		public boolean handleMessage(Message msg) {
			 System.out.println("current thread="+Thread.currentThread().getName());
			return true;
		}
		
		
    	
    }
}

你可能感兴趣的:(HandlerThread)