【问题标题】:How do I stop my AsyncTask?如何停止我的 AsyncTask?
【发布时间】:2017-03-02 23:49:31
【问题描述】:

当应用程序打开时,我的 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();
}

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    首先,您需要引用您的AsyncTask 实例。比方说

    DownloadFileAsync mTask;
    

    您需要致电:

    mTask.cancel(true);
    

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

    if(isCancelled) {
        // exit
    }
    

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

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

    【讨论】:

    • 第一个是全局变量。当您需要启动 AsyncTask 时,请执行 mTask = new DownloadFileAsync(); 并启动它 mTask.execute(your_input); 然后当您想停止 AsyncTask 时,只需调用 mTask.cancel(true)。 isCancelled() 在 doInBackground example 内部使用
    • 我不明白)你能发个sn-p吗?
    【解决方案2】:

    onDestroy() 中使用yourtask.cancel()

    使用此链接了解更多信息:Android - Cancel AsyncTask Forcefully

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多