当前位置:操作系统 > 安卓/Android >>

Android中Handler详解

本文通过例子来验证和说明使用Handler对象开启的线程是否和主线程为在同一线程中。

程序结构图如下:

  



[1] HandlerActivity.java中的源码如下:
[html]
• package com.andyidea.handlerdemo2; 
•  
• import android.app.Activity; 
• import android.os.Bundle; 
• import android.os.Handler; 
• import android.os.HandlerThread; 
• import android.os.Looper; 
• import android.os.Message; 
• import android.util.Log; 
•  
• public class HandlerActivity extends Activity { 
•      
•     private Handler handler = new Handler(); 
•      
•     @Override 
•     public void onCreate(Bundle savedInstanceState) { 
•         super.onCreate(savedInstanceState); 
•         //handler.post(r); 
•         setContentView(R.layout.main); 
•         Log.e("activity-->" ,Thread.currentThread().getId() + ""); 
•         Log.e("activityname-->" ,Thread.currentThread().getName() + ""); 
•         
•         //与主线程同一线程 
•         handler.post(r); 
•          
•         //与主线程不同线程 
•         HandlerThread handlerThread = new HandlerThread("handler_thread"); 
•         handlerThread.start(); 
•         //HandlerThread线程对象要启动后, 
•         //通过handlerThread.getLooper()方法才能获得Looper对象 
•         MyHandler myHandler = new MyHandler(handlerThread.getLooper()); 
•         Message msg  = myHandler.obtainMessage(); 
•         msg.sendToTarget();  //发送消息的方式 
•     } 
•      
•     //创建一个线程对象 www..zzzyk.com  
•     Runnable r = new Runnable() { 
•          
•         @Override 
•         public void run() { 
•             Log.e("handler-->" ,Thread.currentThread().getId() + ""); 
•             Log.e("handlername-->" ,Thread.currentThread().getName() + ""); 
•             try{ 
•                 Thread.sleep(10*1000); 
•             }catch(InterruptedException e){ 
•                 e.printStackTrace(); 
•             } 
•         } 
•     }; 
•      
•     //创建Handler对象 
•     class MyHandler extends Handler{ 
•          
•         public MyHandler(){ 
•              
•         } 
•          
•         public MyHandler(Looper looper){ 
•             super(looper); 
•         } 
•  
•         @Override 
•         public void handleMessage(Message msg) { 
•             Log.e("handler-->" ,Thread.currentThread().getId() + ""); 
•             Log.e("handler-->" ,Thread.currentThread().getName() + ""); 
•         } 
•          
•     } 
• } 
 
运行程序后,我们通过Logcat控制台的log.e输出可以看到结果如下:
 
 
 


通过验证,可以看到如果只是通过Handler对象的post()方法,只是把一个子线程对象放到主线程队列中,并不是开启了一个子线程。通过HandlerThread对象方式才是开启了一个新的线程去执行程序。



摘自  黎明&岁月
 

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,