转自:http://blog.csdn.net/jianghuiquan/article/details/8641072
本章着重通过一个网络通信应用再次了解一下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"/>
四、运行结果