How do I stop my AsyncTask?

时间:2017-03-02 23:49:32

标签: android android-asynctask

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();
}

2 个答案:

答案 0 :(得分:0)

yourtask.cancel()中使用onDestroy()

使用此链接可获得更多说明:Android - Cancel AsyncTask Forcefully

答案 1 :(得分:0)

首先,您需要引用AsyncTask实例。让我们说

DownloadFileAsync mTask;

您需要致电:

mTask.cancel(true);

这仍然不够。在doInBackground()方法中,您必须检查AsyncTask是否已被取消。

if(isCancelled) {
    // exit
}

在您的情况下,您可以在while内使用此检查,以便在取消任务时关闭流并完成。

注意:如果您不关心在doInBackground()停止工作,调用mTask.cancel(true)就足够了,因为isCancelled()方法是自动的在onPostExecute()

中调用