Android HandlerThread

1、认识HandlerThread

Android里的handler不是另外开启线程来执行的,还是在主UI线程中。如果想另启线程的话,除了可以new一个thread,还可以用HandlerThread来实现。在使用HandlerThread的时候需要实现CallBack接口以重写handlerMessage方法,在handlerMessage方法中来处理自己的逻辑。

2、示例代码

public class TestHandlerActivity extends Activity implements OnClickListener{        
    public Button handlerThreadBTN;   
    MyHandlerThread handlerThread;  
    Handler handler;  
      
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        //打印UI线程的名称   
        System.out.println("onCreate  CurrentThread = " + Thread.currentThread().getName());            
        setContentView(R.layout.main);            
        handlerThreadBTN = (Button) findViewById(R.id.handlerThreadBtn);  
        handlerThreadBTN.setOnClickListener(this);            
        handlerThread = new MyHandlerThread("myHanler");  
        handlerThread.start();  
        //注意: 这里必须用到handler的这个构造器,因为需要把callback传进去,从而使自己的HandlerThread的handlerMessage来替换掉Handler原生的handlerThread   
        handler = new Handler(handlerThread.getLooper(), handlerThread);       
    }  
  
    @Override  
    public void onClick(View v) {  
        //点击按钮后来开启线程   
        handler.sendEmptyMessage(1);  
    }
	
    private class MyHandlerThread extends HandlerThread implements Callback {  
  
        public MyHandlerThread(String name) {  
            super(name);  
        }    
        @Override  
        public boolean handleMessage(Message msg) {  
            //打印线程的名称   
            System.out.println(" handleMessage CurrentThread = " + Thread.currentThread().getName());  
            return true;  
        }         
    }      
}


 

你可能感兴趣的:(handlerthread)