當應用程序打開後,我的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