欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android HandlerThread使用方法详解

程序员文章站 2023-11-26 16:39:46
android handlerthread使用方法详解 handlerthread 继承自thread,内部封装了looper。 首先handler和handlerth...

android handlerthread使用方法详解

handlerthread 继承自thread,内部封装了looper。

首先handler和handlerthread的主要区别是:handler与activity在同一个线程中,handlerthread与activity不在同一个线程,而是别外新的线程中(handler中不能做耗时的操作)。

用法:

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;  
  
  
public class mainactivity extends activity {  
  handlerthread handlerthread = new handlerthread("test");  
  handler handler;  
    
  @override  
  protected void oncreate(bundle savedinstancestate) {  
    super.oncreate(savedinstancestate);  
    setcontentview(r.layout.activity_main);  
    system.out.println("cur_id="+thread.currentthread().getid());  
      
    handlerthread.start();  
    system.out.println("handlerthread.id=" + handlerthread.getid());  
    //post(runnable),只是直接运行了run(),run()内threadid与uithread是一样的  
//   handler = new handler();   
    //post(runnable),将runnable运行在handlerthread中,这是非uithread的  
    handler = new handler(handlerthread.getlooper(), new callback() {  
        
      @override  
      public boolean handlemessage(message msg) {  
        system.out.println("receive message.whata=" + msg.what);  
        if (msg.what == 1) {  
          return true;//不再向外层传递  
        } else {  
          return false; //外层的handlemessage() 继续执行  
        }  
          
      }  
    }) {  
      @override  
      public void handlemessage(message msg) {  
        // todo auto-generated method stub  
        super.handlemessage(msg);  
        system.out.println("receive message.whatb=" + msg.what);  
      }  
    };  
    handler.post(new runnable() {  
        
      @override  
      public void run() {  
        system.out.println("handler_post_cur_id="+thread.currentthread().getid());  
        handler.sendemptymessage(1);  
        handler.sendemptymessage(2);  
      }  
    });  
      
  }  
  
}  

运行结果:

01-23 07:12:31.590: i/system.out(12386): cur_id=1  
01-23 07:12:31.590: i/system.out(12386): handlerthread.id=1866  
01-23 07:12:31.590: i/system.out(12386): handler_post_cur_id=1866  
01-23 07:12:31.600: i/system.out(12386): receive message.whata=1  
01-23 07:12:31.600: i/system.out(12386): receive message.whata=2  
01-23 07:12:31.600: i/system.out(12386): receive message.whatb=2  

如有疑问请留言或到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!