安卓多線程編程系列3:使用handler和message下載網絡圖片

使用handler和message進行網絡操作是多線程編程經常使用的形式,下面我們來一起看一下它的使用方法。

整體思路:觸發一個事件,在這個事件中開啓一個線程,在這個線程中定義消息,在消息中攜帶數據,通過handler發送過去,在handler中的handleMessage中去處理消息,獲取數據。具體而言,在xml文件中放置一個Button控件和一個ImageView控件,在activity中,定義一個MyThread類,繼承Runnable這個類,重寫裏面的run方法,在這個方法中獲取網絡圖片,並將網絡圖片對象賦值給message的obj,把定義的常量IS_FINISH賦值給message的what,發送message,定義一個Handler對象,在這個對象中重寫handleMessage這個方法,在這個方法中獲取到message中傳遞的信息,並將圖片對象綁定到ImageView控件上,根據判斷的what的值,來執行對話框的消失操作。注意在清單文件AndroidManifest.xml中添加網絡授權。

activity_main.xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>
MainActivity.java文件:

package com.example.android_handler_message;
//使用handler和message下載圖片並展示
import java.io.InputStream;

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 org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
//不能在UI主線程中直接訪問網絡
	private Button button;
	private ImageView imageView;
	private String image_path="http://pica.nipic.com/2007-11-09/200711912453162_2.jpg";
	private final int IS_FINISH=1;
	private ProgressDialog dialog=null;
	private Handler handler=new Handler(){
		@Override
		public void handleMessage(android.os.Message msg) {
//			數據的接收
			byte[] data=(byte[])msg.obj;
//			對字節數組進行解碼
			Bitmap bm=BitmapFactory.decodeByteArray(data, 0, data.length);
			imageView.setImageBitmap(bm);
			if(msg.what==IS_FINISH){
				dialog.dismiss();
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button=(Button)findViewById(R.id.button1);
		imageView=(ImageView)findViewById(R.id.imageView1);
//		定義一個滾動條對話框
		dialog=new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("正在下載,請稍後...");
		dialog.setCancelable(false);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
                 new Thread(new MyThread()).start();
                 dialog.show();
			}
		});
	}
	
	public class MyThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			HttpClient httpClient=new DefaultHttpClient();
			HttpGet httpGet=new HttpGet(image_path);
			HttpResponse httpResponse=null;
//			也可以用這種方式操作
//			InputStream inputStream=null;
			try {
				httpResponse=httpClient.execute(httpGet);
				if(httpResponse.getStatusLine().getStatusCode()==200){
//					返回一個輸入流
//					inputStream=httpResponse.getEntity().getContent();
					byte[] data=EntityUtils.toByteArray(httpResponse.getEntity());
//					使用message攜帶數據
//					爲什麼不採用這種方式Message message=new Message();定義消息呢?
//					使用Message message=Message.obtain();可以減少內存空間,sPool這個對象爲空的時候才構建對象
//					如果sPool這個對象不爲空的話,可以從消息池中取出重複使用。
					Message message=Message.obtain();
					message.obj=data;
					message.what=IS_FINISH;
//					handler發送message
					handler.sendMessage(message);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		
	} 

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章