您好,登录后才能下订单哦!
多线程从网络下载图片
利用了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();
}
}
};
}
网络权限
<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml文件中只有两个空间
一个Button按钮 一个ImageView
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。