第81章、Handle-Message-Looper消息机制之二(从零开始学Android)

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

 

一、设计界面

  1、布局文件

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvmsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>


二、程序文件

  打开“src/com.genwoxue.hml/MainActivity.java”文件。
  然后输入以下代码:

package com.genwoxue.hml;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;  
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;  
import android.os.Handler;  
import android.os.Looper;  
import android.os.Message;  
import android.util.Log;  
import android.widget.TextView;  

public class MainActivity extends Activity{  
	      
	    private String TAG = "HandlerTest";  
	    private ReceiveMessageThread receiveMessageThread =null;  
	    private EventHandler mHandler = null;   
	    private TextView tv = null; 
	    ProgressDialog pdialog;    
	    
	    @Override  
	    public void onCreate(Bundle savedInstanceState) {  
	        
	    	super.onCreate(savedInstanceState);  
	        setContentView(R.layout.activity_main);  
	        tv = (TextView)super.findViewById(R.id.tvmsg);  
	        
	        //创建对话框
	        pdialog = new ProgressDialog(this);
	        //设置对话框取消按钮
	        pdialog.setButton("cancel", new DialogInterface.OnClickListener() { 
				public void onClick(DialogInterface dialog, int i) {    
					dialog.cancel();        
				}          
			});          
			
	        //对话对话框取消事件
	        pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {     
				public void onCancel(DialogInterface dialog) {           
					finish();           
				}          
	        });          
    	
	        //初始化对话框
			pdialog.setCancelable(true);   
			pdialog.setMax(100);         
			pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);     
			pdialog.show();       

			tv.setText("正在下载中……"); 
			
			//启动线程
			receiveMessageThread = new ReceiveMessageThread();    
			receiveMessageThread.start();     
			
	    }  
	    
	    
	    //消息处理  
	    class EventHandler extends Handler{  
	        public EventHandler(Looper looper){  
	            super(looper);  
	        }  
	          
	        public EventHandler(){  
	            super();  
	        }  
	        @Override  
	        public void handleMessage(Message msg) {  
	            super.handleMessage(msg);  
	            switch(msg.what){  
	            case 1:  	//消息为1传递进度
	                int pos=Integer.valueOf((String)msg.obj);
	                tv.setText((String)msg.obj); 
	                pdialog.setProgress(pos); 
	                break;  
	            case 2:    //消息为2,显示结果
	                tv.setText((String)msg.obj); 
	                pdialog.dismiss();
	                break;  
	         	default:  
	                Log.e(TAG,(String)msg.obj);  
	                break;  
	            }  
	        }  
	    }  
	     
	    //创建子线程,下载网页文件
	    class ReceiveMessageThread extends Thread {  
	          
	        @Override  
	        public void run(){  
	            Looper.prepare();  
		          System.out.println("thread is start!");
	            	
		        	String result = null;
					try{               
						HttpClient client = new DefaultHttpClient();       
						HttpGet get = new HttpGet("http://www.genwoxue.com");      
						HttpResponse response = client.execute(get);        
						HttpEntity entity = response.getEntity();            
						long length = entity.getContentLength();              
						InputStream is = entity.getContent();                
						System.out.print(length);
						if(is != null) {                     
							ByteArrayOutputStream baos = new ByteArrayOutputStream();          
							byte[] buf = new byte[128];                  
							int ch = -1;                   
							int count = 0;          
							int percent=0;
							while((ch = is.read(buf)) != -1) {        
								baos.write(buf, 0, ch);   
								
								count += ch;                        
								if(length > 0) {        
									
									percent=(int) ((count / (float) length) * 100);
									
									Looper looper = Looper.getMainLooper();    
						            mHandler = new EventHandler(looper);  
						            mHandler.removeMessages(1);
						            Message msg =new Message();
						            if(percent<100){
						            	msg.what=1;
						            	msg.obj= String.valueOf(percent);  
						            }
						            else{
						            	result = new String(baos.toByteArray());
						            	msg.what=2;
						            	msg.obj= String.valueOf(result);
						            }
						            	
							         // 将Message对象送入到main thread的MessageQueue里面   
									 MainActivity.this.mHandler.sendMessage(msg);
							            
									}                         
									Thread.sleep(50);    // 让线程休眠50ms                
								}          
							          
						}              
					} catch(Exception e) {         
						e.printStackTrace();        
					}             
		            
	             Looper.loop();  
	        }  
	    }  
	      
}  


三、配置文件

  打开“AndroidManifest.xml”文件。

  然后输入以下代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.genwoxue.hml"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.genwoxue.hml.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


注意:由于要访问互联网,需要在AndroidManifest.xml文件中添加权限:

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

四、运行结果

   

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋会全

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值