2017-03-02 64 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