Handler机制从网络下载图片

多线程从网络下载图片

创新互联公司是一家集网站建设,六合企业网站建设,六合品牌网站建设,网站定制,六合网站建设报价,网络营销,网络优化,六合网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

利用了handler机制

package com.example.testhandler;

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.app.Activity;

import android.app.ProgressDialog;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;

public class TestHandler extends Activity {

private Button btnDown;

private ImageView img;

private static String p_w_picpath_path = "http://wenwen.soso.com/p/20100322/20100322095024-1008716746.jpg";

private ProgressDialog dialog;

private static int IS_FINISH = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

btnDown = (Button) findViewById(R.id.btnDown);

img = (ImageView) findViewById(R.id.ivSinaImage);

dialog = new ProgressDialog(this);

dialog.setTitle("提示信息");

dialog.setMessage("正在下载中,请稍后...");

dialog.setCancelable(false);

btnDown.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

new Thread(mRunnable).start();

dialog.show();

}

});

}

private Runnable mRunnable = new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

HttpClient httpClient = new DefaultHttpClient();

HttpGet httpGet = new HttpGet(p_w_picpath_path);

HttpResponse httpResponse = null;

try {

httpResponse = httpClient.execute(httpGet);

if (httpResponse.getStatusLine().getStatusCode() == 200) {

byte[] data = EntityUtils.toByteArray(httpResponse

.getEntity());

// 获取一个Message对象,设置what为1

Message msg = Message.obtain();

msg.obj = data;

msg.what = IS_FINISH;

// 发送这个消息到消息队列中

handler.sendMessage(msg);

}

} catch (Exception e) {

e.printStackTrace();

}

}

};

private  Handler handler = new Handler() {

// 在Handler中获取消息,重写handleMessage()方法

@Override

public void handleMessage(Message msg) {            

// 判断消息码是否为1

if(msg.what==IS_FINISH){

byte[] data=(byte[])msg.obj;

Bitmap bmp=BitmapFactory.decodeByteArray(data, 0, data.length);

img.setImageBitmap(bmp);

dialog.dismiss();

}

}

};

}

网络权限

activity_main.xml文件中只有两个空间

一个Button按钮 一个ImageView

Handler机制从网络下载图片


分享标题:Handler机制从网络下载图片
网页链接:http://pwwzsj.com/article/gssgcp.html