2017-03-02 383 views
1

當應用程序打開後,我的asynctask會在後臺下載一個文件,一旦文件被下載,它就開始一個活動。哪個工作正常。問題是,如果我關閉應用程序,我想停止下載和打開活動的asynctask。我試過了,它停止服務,但AsyncTask不停止。如何阻止我的AsyncTask?

class DownloadFileAsync extends AsyncTask<String, String, String> { 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected String doInBackground(String... aurl) { 
     int count; 
     try { 
      URL url = new URL(aurl[0]); 
      URLConnection conexion = url.openConnection(); 
      conexion.connect(); 
      int lenghtOfFile = conexion.getContentLength(); 
      Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 
      InputStream input = new BufferedInputStream(url.openStream()); 
      // OutputStream output = new 
      // FileOutputStream("/sdcard/.temp");//.temp is the image file 
      // name 

      OutputStream output = new FileOutputStream(VersionFile); 
      byte data[] = new byte[1024]; 
      long total = 0; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       publishProgress("" + (int) ((total * 100)/lenghtOfFile)); 
       output.write(data, 0, count); 
      } 
      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (Exception e) { 
     } 
     return null; 
    } 

    protected void onProgressUpdate(String... progress) { 
     Log.d("ANDRO_ASYNC", progress[0]); 
    } 

    @Override 
    protected void onPostExecute(String unused) { 
     //start activity 
     Intent dialogIntent = new Intent(context, 
       NSOMUHBroadcastDisplay.class); 
     dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     startActivity(dialogIntent); 
     // now stop the service 
     context.stopService(new Intent(context, 
       NSOMUHBroadcastService.class)); 
    } 
} 

@Override 
public void onDestroy() { 
    Log.v("SERVICE", "Service killed"); 
    stopService(new Intent(this, NSOMUHBroadcastService.class)); 
    super.onDestroy(); 
} 

回答

0

首先,你需要你的AsyncTask實例的引用。比方說,

DownloadFileAsync mTask; 

你需要調用:

mTask.cancel(true); 

這仍然是不夠的。在您的doInBackground()方法中,您必須檢查AsyncTask是否已被取消。

if(isCancelled) { 
    // exit 
} 

你的情況可能是你可以使用這個檢查你的while內,因此,如果在取消關閉流和完成。

注意:如果你不關心停止在doInBackground()工作,呼籲mTask.cancel(true)就夠了,因爲isCancelled()方法是在onPostExecute()自動調用。

+0

我在哪裏插入這3段代碼? – user352621

+0

第一個是全局變量。當你需要啓動你的'AsyncTask'時,執行'mTask = new DownloadFileAsync();'並啓動它'mTask.execute(your_input);'然後當你想停止你的AsyncTask時,只需調用'mTask.cancel(true)'。 isCancelled()用在'doInBackground' [示例](https://developer.android.com/reference/android/os/AsyncTask.html) – GVillani82

+0

我不明白)你能發佈一個片段嗎? – user352621