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

yourtask.cancel()onDestroy()で使用します。

はより明確にするために、このリンクを使用してください:あなたはあなたのAsyncTaskインスタンスへの参照を必要とするすべてのAndroid - Cancel AsyncTask Forcefully

0

まず。さんは

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

関連する問題