public class MainActivity extends Activity { private ImageView image_load; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.image_load = (ImageView) this.findViewById(R.id.image_load); } public void download(View view) { String url = "http://litchiapi.jstv.com/Attachs/Top/11949/e650e0201de541d2ba91dca202b0fcfe.jpg"; // 調用異步任務,執行網絡訪問,注意聯網要權限 new MyTask(this).execute(url); // 不用提示框時new MyTask()不加加入當前this,不用構造函數, } class MyTask extends AsyncTask<String, Void, byte[]> { /* * //AsyncTask三個重要參數:Params: 是一個可變數組 //Progress:進度條,沒有時寫爲void , * //Result:結果參數,通常爲byte[]數組 */ private ProgressDialog pDialog;// 不用在佈局文件配置這個對話框 public MyTask(Context context) { // 建立提示對話框 pDialog = new ProgressDialog(context);// 當前上下文的對話框 pDialog.setTitle("提示"); pDialog.setMessage("正在下載....."); pDialog.setIcon(R.drawable.ic_launcher); } // 主線程運行, 在doInBackground以前執行 @Override protected void onPreExecute() { super.onPreExecute(); Log.i("MainActivity", "onPreExecute : " + Thread.currentThread().getName()); pDialog.show();// 在doInBackground以前執行,打開對話框 } @Override // 在子線程中調用後臺執行 protected byte[] doInBackground(String... params) { Log.i("MainActivity", "onPostExecute : " + Thread.currentThread().getName()); String url = params[0]; HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { return EntityUtils.toByteArray(response.getEntity()); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } // onPostExecute在主線程中執行,在doInBackground後執行,進行UI更新操做 @Override protected void onPostExecute(byte[] result) { Log.i("MainActivity", "onPostExecute : " + Thread.currentThread().getName()); super.onPostExecute(result); if (result != null) { Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length); image_load.setImageBitmap(bitmap); } else { Toast.makeText(MainActivity.this, "網絡異常!", Toast.LENGTH_SHORT) .show(); } pDialog.dismiss();// 下載完關閉對話框 } } } //佈局 <ImageView android:id="@+id/image_load" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_load" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="download" android:layout_below="@+id/image_load" android:text="下載" />