Android 异步下载图片 -- Runnable 方式
习惯先上图:
主要代码:
public class MainActivity extends Activity {Dialog dialog;Bitmap bitmap; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn=(Button) findViewById(R.id.main_do); btn.setOnClickListener(new OnClickListener(){public void onClick(View arg0) {dialog = ProgressDialog.show(MainActivity.this, "wait", "图片下载中 …", true, true);handler.post(new Runnable(){public void run() {try{//下载图片,随便搜索了个,开始度娘了一张图片,竟然下不下来,坑爹URL url = new URL("http://tupian.qqjay.com/u/2012/0301/cdb1df16018702727988083e1f03b703.jpg"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream inputStream=conn.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); //下载完成,向handler发送消息 Message m=new Message(); m.what=1; handler.sendMessage(m);}catch(Exception e){e.printStackTrace();}}});} }); } private Handler handler=new Handler(){ public void handleMessage(Message msg){ switch(msg.what){ case 1: //更新显示图片,销毁dialog ImageView view=(ImageView)findViewById(R.id.main_pic); view.setImageBitmap(bitmap); dialog.dismiss(); break; } } }; }