Android 如何停止异步任务?

Android 如何停止异步任务?,android,android-asynctask,Android,Android Asynctask,当应用程序打开时,我的asynctask在后台下载一个文件,一旦文件被下载,它就会启动一个活动。这很好用。问题是,如果我关闭应用程序,我想停止asynctask下载和打开活动。我已经试过了,它停止了服务,但是异步任务没有停止 class DownloadFileAsync extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super

当应用程序打开时,我的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();
}
class DownloadFileAsync扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的字符串背景(字符串…aurl){
整数计数;
试一试{
URL=新URL(aurl[0]);
URLConnection conexion=url.openConnection();
conexion.connect();
int lenghtOfFile=conexion.getContentLength();
Log.d(“ANDRO_ASYNC”,“文件长度:“+lenghtOfFile”);
InputStream输入=新的BufferedInputStream(url.openStream());
//OutputStream输出=新
//FileOutputStream(“/sdcard/.temp”);//.temp是映像文件
//名字
OutputStream output=新文件OutputStream(VersionFile);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
出版进度(“+(int)((总计*100)/长度文档));
输出.写入(数据,0,计数);
}
output.flush();
output.close();
input.close();
}捕获(例外e){
}
返回null;
}
受保护的void onProgressUpdate(字符串…进度){
Log.d(“ANDRO_ASYNC”,progress[0]);
}
@凌驾
受保护的void onPostExecute(字符串未使用){
//开始活动
意向对话意向=新意向(上下文,
nsomuh(显示类);
dialogIntent.addFlags(Intent.FLAG\u活动\u新任务);
startActivity(dialogIntent);
//现在停止服务
stopService(新意图)(上下文,
nsomuhservice.class));
}
}
@凌驾
公共空间{
Log.v(“服务”、“服务终止”);
stopService(新意图(这个,NSOMUHBroadcastService.class));
super.ondestory();
}
onDestroy()
中使用
yourtask.cancel()

使用此链接了解更多说明:

ondestory()
中使用
yourtask.cancel()


使用此链接可获得更多说明:

首先,您需要一个对
异步任务
实例的引用。比方说

DownloadFileAsync mTask;
您需要拨打:

mTask.cancel(true);
这还不够。在
doInBackground()
方法中,必须检查
AsyncTask
是否已取消

if(isCancelled) {
    // exit
}
在您的情况下,您可能可以在
中使用此检查,而
,以便在取消任务时关闭流并完成


注意:如果您不想停止
doInBackground()
中的工作,那么调用
mTask.cancel(true)
就足够了,因为iscancell()方法会在
onPostExecute()
中自动调用。首先,您需要一个对
AsyncTask
实例的引用。比方说

DownloadFileAsync mTask;
您需要拨打:

mTask.cancel(true);
这还不够。在
doInBackground()
方法中,必须检查
AsyncTask
是否已取消

if(isCancelled) {
    // exit
}
在您的情况下,您可能可以在
中使用此检查,而
,以便在取消任务时关闭流并完成


注意:如果您不想停止
doInBackground()
中的工作,调用
mTask.cancel(true)
就足够了,因为iscancell()方法是在
onpostsecute()
中自动调用的,第一个方法是全局变量。当您需要启动
AsyncTask
do
mTask=new DownloadFileAsync()时
并启动它
mTask.execute(您的输入)
然后,当您想停止异步任务时,只需调用
mTask.cancel(true)
。isCancelled()用于
doInBackground
I not knowledge)可以发布一个片段吗?第一个是全局变量。当您需要启动
AsyncTask
do
mTask=new DownloadFileAsync()时
并启动它
mTask.execute(您的输入)
然后,当您想停止异步任务时,只需调用
mTask.cancel(true)
。isCancelled()用于
doInBackground
I not knowledge)你能发布一个片段吗?