2017-03-02 2 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 내에서이 검사를 사용할 수 있습니다.

참고 다음의 isCancelled() 메소드가 자동으로 onPostExecute()에 호출되기 때문에 당신이 mTask.cancel(true) 전화는 doInBackground()에서 작업을 중지 걱정하지 않는 경우는 충분하다.

+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

관련 문제