AsyncTask 下载图片
package com.test.network; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Objects; /** * AsyncTask 实现图片下载、显示 */ public class AsyncDownLoadActivity extends AppCompatActivity { private String urlPath = "http://img4.imgtn.bdimg.com/it/u=3340865222,3464212128&fm=21&gp=0.jpg"; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_async_down_load); imageView = (ImageView) findViewById(R.id.imageView); new AsynPicTask().execute(imageView, urlPath); } class AsynPicTask extends AsyncTask<Object, Object, Bitmap> { private ImageView imageView; protected void onPreExecute() { } //执行耗时操作 @Override protected Bitmap doInBackground(Object... params) { imageView = (ImageView) params[0]; Bitmap bitmap = null; try { URL url = new URL((String) params[1]); URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(3000); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); inputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } protected void onProgressUpdate(Object... values) { } //耗时操作返回结果 protected void onPostExecute(Bitmap result) { imageView.setImageBitmap(result); } } }