Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android技術基礎 >> 第81章、Handle-Message-Looper消息機制之二(從零開始學Android)

第81章、Handle-Message-Looper消息機制之二(從零開始學Android)

編輯:Android技術基礎

本章著重通過一個網絡通信應用再次了解一下Handle、Message、Looper實際用法。

 

一、設計界面

1、布局文件

打開res/layout/activity_main.xml文件。
輸入以下代碼:

[html] view plain copy  
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout   
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <TextView  
  9.         android:id="@+id/tvmsg"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="" />  
  13.   
  14. </LinearLayout>  

 

二、程序文件

打開“src/com.genwoxue.hml/MainActivity.java”文件。
然後輸入以下代碼:

[java] view plain copy  
  1. package com.genwoxue.hml;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.InputStream;  
  5.   
  6. import org.apache.http.HttpEntity;  
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.client.HttpClient;  
  9. import org.apache.http.client.methods.HttpGet;  
  10. import org.apache.http.impl.client.DefaultHttpClient;  
  11. import android.app.Activity;    
  12. import android.app.ProgressDialog;  
  13. import android.content.DialogInterface;  
  14. import android.os.Bundle;    
  15. import android.os.Handler;    
  16. import android.os.Looper;    
  17. import android.os.Message;    
  18. import android.util.Log;    
  19. import android.widget.TextView;    
  20.   
  21. public class MainActivity extends Activity{    
  22.             
  23.         private String TAG = "HandlerTest";    
  24.         private ReceiveMessageThread receiveMessageThread =null;    
  25.         private EventHandler mHandler = null;     
  26.         private TextView tv = null;   
  27.         ProgressDialog pdialog;      
  28.           
  29.         @Override    
  30.         public void onCreate(Bundle savedInstanceState) {    
  31.               
  32.             super.onCreate(savedInstanceState);    
  33.             setContentView(R.layout.activity_main);    
  34.             tv = (TextView)super.findViewById(R.id.tvmsg);    
  35.               
  36.             //創建對話框  
  37.             pdialog = new ProgressDialog(this);  
  38.             //設置對話框取消按鈕  
  39.             pdialog.setButton("cancel", new DialogInterface.OnClickListener() {   
  40.                 public void onClick(DialogInterface dialog, int i) {      
  41.                     dialog.cancel();          
  42.                 }            
  43.             });            
  44.               
  45.             //對話對話框取消事件  
  46.             pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {       
  47.                 public void onCancel(DialogInterface dialog) {             
  48.                     finish();             
  49.                 }            
  50.             });            
  51.           
  52.             //初始化對話框  
  53.             pdialog.setCancelable(true);     
  54.             pdialog.setMax(100);           
  55.             pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);       
  56.             pdialog.show();         
  57.   
  58.             tv.setText("正在下載中……");   
  59.               
  60.             //啟動線程  
  61.             receiveMessageThread = new ReceiveMessageThread();      
  62.             receiveMessageThread.start();       
  63.               
  64.         }    
  65.           
  66.           
  67.         //消息處理    
  68.         class EventHandler extends Handler{    
  69.             public EventHandler(Looper looper){    
  70.                 super(looper);    
  71.             }    
  72.                 
  73.             public EventHandler(){    
  74.                 super();    
  75.             }    
  76.             @Override    
  77.             public void handleMessage(Message msg) {    
  78.                 super.handleMessage(msg);    
  79.                 switch(msg.what){    
  80.                 case 1:     //消息為1傳遞進度  
  81.                     int pos=Integer.valueOf((String)msg.obj);  
  82.                     tv.setText((String)msg.obj);   
  83.                     pdialog.setProgress(pos);   
  84.                     break;    
  85.                 case 2:    //消息為2,顯示結果  
  86.                     tv.setText((String)msg.obj);   
  87.                     pdialog.dismiss();  
  88.                     break;    
  89.                 default:    
  90.                     Log.e(TAG,(String)msg.obj);    
  91.                     break;    
  92.                 }    
  93.             }    
  94.         }    
  95.            
  96.         //創建子線程,下載網頁文件  
  97.         class ReceiveMessageThread extends Thread {    
  98.                 
  99.             @Override    
  100.             public void run(){    
  101.                 Looper.prepare();    
  102.                   System.out.println("thread is start!");  
  103.                       
  104.                     String result = null;  
  105.                     try{                 
  106.                         HttpClient client = new DefaultHttpClient();         
  107.                         HttpGet get = new HttpGet("http://www.genwoxue.com");        
  108.                         HttpResponse response = client.execute(get);          
  109.                         HttpEntity entity = response.getEntity();              
  110.                         long length = entity.getContentLength();                
  111.                         InputStream is = entity.getContent();                  
  112.                         System.out.print(length);  
  113.                         if(is != null) {                       
  114.                             ByteArrayOutputStream baos = new ByteArrayOutputStream();            
  115.                             byte[] buf = new byte[128];                    
  116.                             int ch = -1;                     
  117.                             int count = 0;            
  118.                             int percent=0;  
  119.                             while((ch = is.read(buf)) != -1) {          
  120.                                 baos.write(buf, 0, ch);     
  121.                                   
  122.                                 count += ch;                          
  123.                                 if(length > 0) {          
  124.                                       
  125.                                     percent=(int) ((count / (float) length) * 100);  
  126.                                       
  127.                                     Looper looper = Looper.getMainLooper();      
  128.                                     mHandler = new EventHandler(looper);    
  129.                                     mHandler.removeMessages(1);  
  130.                                     Message msg =new Message();  
  131.                                     if(percent<100){  
  132.                                         msg.what=1;  
  133.                                         msg.obj= String.valueOf(percent);    
  134.                                     }  
  135.                                     else{  
  136.                                         result = new String(baos.toByteArray());  
  137.                                         msg.what=2;  
  138.                                         msg.obj= String.valueOf(result);  
  139.                                     }  
  140.                                           
  141.                                      // 將Message對象送入到main thread的MessageQueue裡面     
  142.                                      MainActivity.this.mHandler.sendMessage(msg);  
  143.                                           
  144.                                     }                           
  145.                                     Thread.sleep(50);    // 讓線程休眠50ms                  
  146.                                 }            
  147.                                         
  148.                         }                
  149.                     } catch(Exception e) {           
  150.                         e.printStackTrace();          
  151.                     }               
  152.                       
  153.                  Looper.loop();    
  154.             }    
  155.         }    
  156.             
  157. }    

 

三、配置文件

打開“AndroidManifest.xml”文件。

然後輸入以下代碼:

[html] view plain copy  
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.genwoxue.hml"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="10"  
  9.         android:targetSdkVersion="15" />  
  10.       
  11.     <uses-permission android:name="android.permission.INTERNET"/>  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.genwoxue.hml.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.                 <category android:name="android.intent.category.LAUNCHER" />  
  24.             </intent-filter>  
  25.         </activity>  
  26.     </application>  
  27.   
  28. </manifest>  

 

注意:由於要訪問互聯網,需要在AndroidManifest.xml文件中添加權限:

<uses-permission android:name="android.permission.INTERNET"/>

四、運行結果

\ \

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved