내 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