首页 > 代码库 > Android多线程——Handler (一) 实现图片下载
Android多线程——Handler (一) 实现图片下载
在UI线程中创建子线程——》在子线程中获取网络图片--》在线程中通过Message 传递二进制图片给Handler,--》Handler在handleMessage()中处理消息
package com.example.android_handler_message; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; 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 { private static int IS_FINISHED = 1; private Button button = null; private ImageView imageView = null; private String image_path = "http://i1.juyouqu.com/uploads/content//2014/04/1396611698344.jpg!w598"; private ProgressDialog dialog = null; private Handler handle = new Handler(){ public void handleMessage(android.os.Message msg) { Bitmap bitmap = null; byte[] data = http://www.mamicode.com/(byte[])msg.obj;"提示"); dialog.setMessage("正在下载.........."); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new Thread(new MyTask()).start(); dialog.show(); } }); } public class MyTask implements Runnable { @Override public void run() { // TODO Auto-generated method stub HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(image_path); try { HttpResponse httpResponse = httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode() == 200) { byte[] data = http://www.mamicode.com/EntityUtils.toByteArray(httpResponse.getEntity());>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。