1

My asynctask downloads a file in background when the app is opened, once the file gets downloaded, it starts an activity. Which is working fine. The problem is, I want to STOP my asynctask from downloading and opening activity if I close the app. I have tried this, It stops the service, but the AsyncTask doesn't stop.

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();
}
user352621
  • 23
  • 3

2 Answers2

0

use yourtask.cancel() in onDestroy().

Use this link for more clarification: Android - Cancel AsyncTask Forcefully

Community
  • 1
  • 1
Asif Patel
  • 1,744
  • 1
  • 20
  • 27
0

First of all you need a reference to your AsyncTask instance. Let's say

DownloadFileAsync mTask;

You need to call:

mTask.cancel(true);

This is still not enough. Inside your doInBackground() method, you have to check if the AsyncTask has been cancelled.

if(isCancelled) {
    // exit
}

In your case probably you can use this check inside your while, so that if the Task is cancelled you close the stream and finish.

NOTE: In case you don't care about stopping the work in the doInBackground(), calling mTask.cancel(true) is enough, because the isCancelled() method is automatically called in the onPostExecute().

GVillani82
  • 17,196
  • 30
  • 105
  • 172
  • The first one is a global variable. When you need to start your `AsyncTask` do `mTask = new DownloadFileAsync();` and start it `mTask.execute(your_input);` Then when you want to stop your AsyncTask just call `mTask.cancel(true)`. The isCancelled() is used inside the `doInBackground` [example](https://developer.android.com/reference/android/os/AsyncTask.html) – GVillani82 Mar 03 '17 at 00:17
  • I not understand) could you post a snippet, ? – user352621 Mar 03 '17 at 00:29