2016-02-27 2 views
0

Привет, У меня есть задача async, которая загружает изображение через HTTP-запрос и делится им после завершения. Но если пользователь отменит задачу, он должен остановиться.Отменить Async Task во время загрузки изображения

Я звоню это так:

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")); 

    } 

} 

ответ

0

Вызов метода "mShareImage.cancel (истина)" будет вызывать последующие вызовы isCancelled(), чтобы вернуться верно. Но вы должны сделать несколько вещей,

  • Для того, чтобы задача отменена как можно быстрее, вы должны всегда проверять возвращаемое значение isCancelled() периодически внутри doInBackground.
  • Вы установили «! 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")); 

} 
Смежные вопросы