当应用程序打开后,我的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();
}
我在哪里插入这3段代码? – user352621
第一个是全局变量。当你需要启动你的'AsyncTask'时,执行'mTask = new DownloadFileAsync();'并启动它'mTask.execute(your_input);'然后当你想停止你的AsyncTask时,只需调用'mTask.cancel(true)'。 isCancelled()用在'doInBackground' [示例](https://developer.android.com/reference/android/os/AsyncTask.html) – GVillani82
我不明白)你能发布一个片段吗? – user352621