(Android) Download Images by AsyncTask API

1. Check network status

AndroidManifest.xml

<uses-sdk> ... </>

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

<application>

 

MainActivity.java

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 ExecutorThreadPoolExecutor 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,doInBackgroundonProgressUpdate andonPostExecute.

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

 private ImageView view;
 private Bitmap img;

 public ImageDownload(ImageView view) {
  this.view = view;
 }

 @Override
 protected Boolean doInBackground(String... urls) {
  try {
   URL imageUrl = new URL(urls[0]);
   URLConnection conn = imageUrl.openConnection();
   img = BitmapFactory.decodeStream(conn.getInputStream());

  } catch (MalformedURLException e) {
   e.printStackTrace();
   return false;
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }
  return true;
 }

 @Override
 protected void onPostExecute(Boolean downloadResult) {
  if (downloadResult) {
   view.setImageBitmap(img);
  }
 }
 
 protected void onProgressUpdate(Integer... progress) {
        //Set progress
    }

}

 

 

3. Begin to download images

String[] urls = new String[1];
urls[0] = "http://media.zenfs.com/ko_KR/News/starnn/20130121130545_50fcbe998c3d0_1.jpg";
ImageDownload imageDownload = new ImageDownload(imageDownloadView);
imageDownload.execute(urls);



新增了二个预定义的线程池SERIAL_EXECUTORTHREAD_POOL_EXECUTOR


其实THREAD_POOL_EXECUTOR并不是新增的,之前的就有,只不过之前(Android 2.3)它是AsyncTask私有的,未公开而已。THREAD_POOL_EXECUTOR是一个corePoolSize为5的线程池,也就是说最多只有5个线程同时运行,超过5个的就要等待。所以如果使用executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)就跟2.3版本的AsyncTask.execute()效果是一样的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值