Android多线程——Handler(一)实现图片下载-创新互联
在UI线程中创建子线程——》在子线程中获取网络图片--》在线程中通过Message 传递二进制图片给Handler,--》Handler在handleMessage()中处理消息
成都创新互联主营甘泉网站建设的网络公司,主营网站建设方案,成都app开发,甘泉h5微信小程序开发搭建,甘泉网站营销推广欢迎甘泉等地区企业咨询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 p_w_picpathView = null; private String p_w_picpath_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 = (byte[])msg.obj; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); if(msg.what == IS_FINISHED) { dialog.dismiss(); p_w_picpathView.setImageBitmap(bitmap); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button1); p_w_picpathView = (ImageView)findViewById(R.id.p_w_picpathView1); dialog = new ProgressDialog(this); dialog.setTitle("提示"); 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(p_w_picpath_path); try { HttpResponse httpResponse = httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode() == 200) { byte[] data = EntityUtils.toByteArray(httpResponse.getEntity()); Message message = Message.obtain(); message.obj = data; message.what = IS_FINISHED; handle.sendMessage(message); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
当前标题:Android多线程——Handler(一)实现图片下载-创新互联
标题来源:http://ybzwz.com/article/cophdg.html