使用AsyncTask下载多张网络图片,并保存到本地

使用AsyncTask下载多张网络图片

for (int i =0; i < item.getUrls().size();i++){

    new AsynPicTask().execute(item.getUrls().get(i));

}

在onPostExecute回调方法里保存下载好的图片

class AsynPicTaskextends AsyncTask {

    @Override

    protected BitmapdoInBackground(String... imagUrl) {

        Bitmap bitmap =null;

            try {

                URL url =new URL(imagUrl[0]);

                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;

    }

    @Override

    protected void onPreExecute() {

        super.onPreExecute();

    }

    @SuppressLint("WrongThread")

    @Override

    protected void onPostExecute(Bitmap bitmap) {

        // 首先保存图片

        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +"akxy";

        File appDir =new File(storePath);

        if (!appDir.exists()) {

            appDir.mkdir();

        }

        String fileName = System.currentTimeMillis() +".jpg";

            File file =new File(appDir, fileName);

            try {

                    FileOutputStream fos =new FileOutputStream(file);

                    //通过io流的方式来压缩保存图片

                    if(bitmap!=null) {

                        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);

                        fos.flush();

                        fos.close();

               }

            //保存图片后发送广播通知更新数据库

            Uri uri = Uri.fromFile(file);

            mcontext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

        }catch (IOException e) {

            e.printStackTrace();

        }

    }

}

你可能感兴趣的:(使用AsyncTask下载多张网络图片,并保存到本地)