下载图像时取消异步任务

时间:2016-02-27 03:24:24

标签: java android android-asynctask

嗨, 我有一个异步任务,通过http请求下载图像并在完成后共享它。但如果用户取消任务,则应该停止。

我称之为:

mShareImage = new shareAsync(PhotoEnlargeActivity.this).execute(imageUris.get(currentPosition));

并按此停止:

mShareImage.cancel(true);

但它看起来没有用。异步任务:

public class shareAsync extends AsyncTask<String, String, String> {
    private Context mContext;
    URL myFileUrl;

    Bitmap bmImg = null;
    Intent share;
    File file;
    boolean isCancelled = false;

    public shareAsync(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        isCancelled = true;
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub

        super.onPreExecute();
        showProgressDialog("Downloading High Resolution Image for Sharing...");

    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        HttpURLConnection conn = null;

        try {
            if (!isCancelled()) {
                myFileUrl = new URL(args[0]);
                conn = (HttpURLConnection) myFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();
                bmImg = BitmapFactory.decodeStream(is);
            } else {
                if (conn != null) conn.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {

            String path = myFileUrl.getPath();
            String idStr = path.substring(path.lastIndexOf('/') + 1);
            File filepath = Environment.getExternalStorageDirectory();
            File dir = new File(filepath.getAbsolutePath()
                    + "/Google Image Wallpaper/");
            dir.mkdirs();
            String fileName = idStr;
            file = new File(dir, fileName);
            FileOutputStream fos = new FileOutputStream(file);
            bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String args) {
        // TODO Auto-generated method stub
        progressDialog.dismiss();
        share = new Intent(Intent.ACTION_SEND);
        share.setType("image/jpeg");

        share.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getAbsolutePath().toString()));

        mContext.startActivity(Intent.createChooser(share, "Share Image"));

    }

}

1 个答案:

答案 0 :(得分:0)

调用方法“mShareImage.cancel(true)”将导致后续调用isCancelled()返回true。 但你必须做更多的事情,

  • 为了确保尽快取消任务,您应该始终在doInBackground内定期检查isCancelled()的返回值。
  • 您已添加“!isCancelled()”检查方法的开头,因此无效。
  • 网络操作是阻塞操作,因此一旦启动任何操作,您必须等待。这就是为什么我们总是在工作线程中进行网络操作。

以下更改可以解决您的问题,

 @Override
protected String doInBackground(String... args) {
    // TODO Auto-generated method stub
    HttpURLConnection conn = null;

    try {
            myFileUrl = new URL(args[0]);
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            if (isCancelled()) return null;
            conn.connect();
            if (isCancelled()) return null;
            InputStream is = conn.getInputStream();
            if (isCancelled()) return null;
            bmImg = BitmapFactory.decodeStream(is);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
            conn = null;
        }
    }

    try {

        String path = myFileUrl.getPath();
        String idStr = path.substring(path.lastIndexOf('/') + 1);
        File filepath = Environment.getExternalStorageDirectory();
        File dir = new File(filepath.getAbsolutePath()
                + "/Google Image Wallpaper/");
        dir.mkdirs();
        String fileName = idStr;
        file = new File(dir, fileName);
        FileOutputStream fos = new FileOutputStream(file);
        if (isCancelled()) return null;
        bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

@Override
protected void onPostExecute(String args) {
    // TODO Auto-generated method stub
    progressDialog.dismiss();
    share = new Intent(Intent.ACTION_SEND);
    share.setType("image/jpeg");

    share.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getAbsolutePath().toString()));
    if (isCancelled()) return;
    mContext.startActivity(Intent.createChooser(share, "Share Image"));

}
相关问题