Моя асинхронная задача загружает файл в фоновом режиме, когда приложение открыто, после загрузки файла оно запускает действие. Который работает нормально. Проблема в том, что я хочу остановить загрузку и открытие моей асинхронной задачи, если я закрою приложение. Я пробовал это, он останавливает службу, но 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();
}
AsyncTask
, сделайтеmTask = new DownloadFileAsync();
и запустите егоmTask.execute(your_input);
Затем, когда вы захотите остановить свою AsyncTask, просто вызовитеmTask.cancel(true)
. isCancelled() используется внутриdoInBackground
примера 03.03.2017