(Android) Download Images by AsyncTask API

  次阅读 来源:互联网(转载协议) 2016-01-14 12:42 我要评论(0)

1. Check network status


<uses-sdk> ... </>

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



public boolean isNetworkAvailable() {

ConnectivityManager connectivityManager

= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

return activeNetworkInfo != null && activeNetworkInfo.isConnected();


2. Extends AsyncTask to download images.

Normally, we create mutl-thread which is used to download images.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread andHandler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by thejava.util.concurrent pacakge such as Executor, ThreadPoolExecutor andFutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, calledParams, Progress and Result, and 4 steps, called onPreExecute, doInBackground,onProgressUpdate andonPostExecute.

public class ImageDownload extends AsyncTask<String, Integer, Boolean> {

private ImageView view;

private Bitmap img;

public ImageDownload(ImageView view) {

this.view = view;



protected Boolean doInBackground(String... urls) {

try {

URL imageUrl = new URL(urls[0]);

URLConnection conn = imageUrl.openConnection();

img = BitmapFactory.decodeStream(conn.getInputStream());

} catch (MalformedURLException e) {


return false;

} catch (IOException e) {


return false;


return true;



protected void onPostExecute(Boolean downloadResult) {

if (downloadResult) {




protected void onProgressUpdate(Integer... progress) {

//Set progress



  • Oculus公布原型机,大幅度提升可视角,能实现140°的视场水平


  • teamLab创始人猪子寿之: 抛去衣食住行,我还剩下什么?

    teamLab创始人猪子寿之: 抛去衣食住行,我还剩下什么?

  • Michael I. Jordan带你解读百万奖金ATEC蚂蚁人工智能大赛

    Michael I. Jordan带你解读百万奖金ATEC蚂蚁人工智能大赛

  • 2018深圳国际人工智能展览会 2018 shenzhen International Artif

    2018深圳国际人工智能展览会 2018 shenzhen International Artif



近日,美国软性机器抓手制造商 Soft Robotics 宣布,获得 2000 万美元的融资,本轮投资者包括 Scale Venture Partners,Calibrate Ventures...

据外媒报道,加州车管局发布了《2017自动驾驶脱离报告(California Autonomous Vehicle Disengagement Reports)》,其中谈及了脱离的具体...