zoukankan      html  css  js  c++  java
  • 第81章、Handle-Message-Looper消息机制之二(从零开始学Android)

    转自:http://blog.csdn.net/jianghuiquan/article/details/8641072

    本章着重通过一个网络通信应用再次了解一下Handle、Message、Looper实际用法。

     

    一、设计界面

      1、布局文件

      打开res/layout/activity_main.xml文件。
      输入以下代码:

    [html] view plaincopy
    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 plaincopy
    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 plaincopy
    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"/>

    四、运行结果

       


  • 相关阅读:
    POJ 1611 The Suspects
    POJ 2001 Shortest Prefixes(字典树)
    HDU 1251 统计难题(字典树 裸题 链表做法)
    G++ C++之区别
    PAT 乙级 1013. 数素数 (20)
    PAT 乙级 1012. 数字分类 (20)
    PAT 乙级 1009. 说反话 (20)
    PAT 乙级 1008. 数组元素循环右移问题 (20)
    HDU 6063 17多校3 RXD and math(暴力打表题)
    HDU 6066 17多校3 RXD's date(超水题)
  • 原文地址:https://www.cnblogs.com/walccott/p/4957603.html
Copyright © 2011-2022 走看看