How to completely kill / delete / delete / stop AsyncTask

I made an application that downloads video from our server. The problem is this:

When I cancel the download, I call:

myAsyncTask.cancel(true) 

I noticed that myAsyncTask does not stop when cancel is called ... my ProgressDialog is still going up, and this is like switching from status to status, showing that every time I cancel and start AsyncTask again by clicking the download button, it starts new AsyncTask ... Each time I click the Download button, then cancel, and then load a separate AsyncTask launch AsyncTask .

Why doesn't myAsynTask.cancle(true) cancel my task? I no longer want this in the background. I just want to completely close it if I click cancel.

How to do it?

ED i T:

Thanks to gtumca-MAC and others who helped me, this helped:

 while (((count = input.read(data)) != -1) && (this.isCancelled()==false)) { total += count; publishProgress((int) (total * 100 / lenghtOfFile)); output.write(data, 0, count); } 

Thank!!!

+26
android android-asynctask
Jun 04 2018-12-12T00:
source share
7 answers

AsyncTask does not cancel the process on

 myAsynTask.cancel(true) 

To do this, you need to stop it manually.

for example, you upload a video to doInBackground(..) in a while / for loop.

 protected Long doInBackground(URL... urls) { for (int i = 0; i < count; i++) { // you need to break your loop on particular condition here if(isCancelled()) break; } return totalSize; } 
+56
Jun 04 '12 at 13:59
source share

Declare in class

 DownloadFileAsync downloadFile = new DownloadFileAsync(); 

then click "Create"

 DownloadFileAsync downloadFile = new DownloadFileAsync(); downloadFile.execute(url); 

in the background()

 if (isCancelled()) break; @Override protected void onCancelled(){ } 

and you can kill your AsyncTask with

 downloadFile.cancel(true); 
+4
Jun 22 '13 at 11:03
source share

When you start a separate thread (AyncTask), it should end. You must manually add the cancel statement to your code inside AsyncTask.

A task can be canceled at any time by calling cancel (boolean). Calling this method will result in subsequent calls to isCancelled () to return true. After calling this method, onCancelled (Object) will be called instead of onPostExecute (Object) after doInBackground (Object []) returns. To ensure that the task is canceled as quickly as possible, you should always check the returned value of isCancelled () periodically from doInBackground (Object []), if possible (inside a loop, for example.)

Additional documentation information: http://developer.android.com/reference/android/os/AsyncTask.html

+1
Jun 04 2018-12-12T00:
source share

I have been doing research for the last 2 weeks and I don’t know how we kill Async operation manually. Some developers use BREAK ;, checking the loop. But in my scenario, I do not use a loop inside the background thread. But I have to know how this awakens his silly logic, but it works just fine.

 downloadFile.cancel(true); //This code wont work in any case. 

Instead of undoing and doing so much work in the background thread, disable wifi programmatically

 WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(false); 

where you want to kill the operation and turn it on where you need it.

 WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(true); 

What happens, your try block goes into an IOException, killing background tasks.

0
Jan 12 '15 at 7:46
source share

It is better to use the vogella asyncTask library, which has many functions such as priority and cancellation of the background task. And a great tutorial or its use here

0
Jan 12 '15 at 8:09
source share

You can use this code. I upload the OTA file as follows:

 static class FirmwareDownload extends AsyncTask<String, String, String> { public String TAG = "Super LOG"; public String file; int lenghtOfFile; long total; @Override protected String doInBackground(String... f_url) { try { int count; Utilies.getInternet(); URL url = new URL(f_url[0]); URLConnection connection = url.openConnection(); connection.connect(); lenghtOfFile = connection.getContentLength(); mProgressBar.setMax(lenghtOfFile); InputStream input = new BufferedInputStream(url.openStream(), 8192); String fileName = f_url[0].substring(f_url[0].lastIndexOf("/"), f_url[0].length()); File root = Environment.getExternalStorageDirectory(); File dir = new File(root.getAbsolutePath() + fileName); Log.d(TAG, "trying to download in : " + dir); dir.getAbsolutePath(); OutputStream output = new FileOutputStream(dir); byte data[] = new byte[1024]; while ((count = input.read(data)) != -1) { if (isCancelled()) break; total += count; mProgressBar.setProgress(Integer.parseInt("" + total)); Log.d("Downloading " + fileName + " : ", " " + (int) ((total * 100) / lenghtOfFile)); mPercentage.post(new Runnable() { @Override public void run() { mPercentage.setText(total / (1024 * 1024) + " Mb / " + lenghtOfFile / (1024 * 1024) + " Mb"); } }); output.write(data, 0, count); } output.flush(); output.close(); input.close(); //new InstallHelper().commandLine("mkdir data/data/ota"); File fDest = new File("/data/data/ota/" + fileName); copyFile(dir, fDest); FirmwareInstaller fw = new FirmwareInstaller(); fw.updateFirmware(); } catch (Exception a) { System.out.println("Error trying donwloading firmware " + a); new InstallHelper().commandLine("rm -r data/data/ota"); dialog.dismiss(); } return null; } } 

So, if you want to cancel, just use this code:

  fDownload.cancel(true); 
0
Sep 11 '15 at 14:34
source share

I used with success inside the action with TextView onclick ...

  //inside the doInBackground() ... try { while (true) { System.out.println(new Date()); //should be 1 * 1000 for second Thread.sleep(5 * 1000); if (isCancelled()) { return null; } } } catch (InterruptedException e) { } 

and in my onCreate () ...

  //set Activity final SplashActivity sPlashScreen = this; //init my Async Task final RetrieveFeedTask syncDo = new RetrieveFeedTask(); syncDo.execute(); //init skip link skip_text = (TextView) findViewById(R.id.skip_text); skip_text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //cancel Async syncDo.cancel(true); //goto/start another activity Intent intent = new Intent(); intent.setClass(sPlashScreen, MainActivity.class); startActivity(intent); finish(); } }); 

and my TextView xml element ...

  <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/skip_text" android:layout_marginTop="20dp" android:text="SKIP" android:textColor="@color/colorAccent"/> 
0
Mar 05 '17 at 4:47 on
source share



All Articles