How to completely kill/remove/delete/stop an AsyncTask
我制作了一个可从我们的服务器下载视频的应用。
问题是:
当我取消下载时,我会致电:
1 | myAsyncTask.cancel(true) |
我注意到,
每次单击下载..然后取消,然后再次下载一个单独的
为什么
怎么做 ?
E D I T:
多亏了gtumca-MAC,以及其他帮助我做到这一点的人:
1 2 3 4 5 6 | while (((count = input.read(data)) != -1) && (this.isCancelled()==false)) { total += count; publishProgress((int) (total * 100 / lenghtOfFile)); output.write(data, 0, count); } |
谢谢!!!
AsyncTask不会取消进程
1 | myAsynTask.cancel(true) |
为此,您必须手动停止它。
例如,您正在while / for循环中的
1 2 3 4 5 6 7 8 9 10 | 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; } |
在类上声明
1 | DownloadFileAsync downloadFile = new DownloadFileAsync(); |
然后在创建时
1 2 | DownloadFileAsync downloadFile = new DownloadFileAsync(); downloadFile.execute(url); |
在您的背景中()
1 2 3 4 5 6 7 | if (isCancelled()) break; @Override protected void onCancelled(){ } |
你可以通过杀死你的AsyncTask
1 | downloadFile.cancel(true); |
当您启动一个单独的线程(AyncTask)时,它必须完成。您必须在AsyncTask中的代码中手动添加一个cancel语句。
可以通过调用cancel(boolean)随时取消任务。调用此方法将导致对isCancelled()的后续调用返回true。调用此方法后,在doInBackground(Object [])返回之后,将调用onCancelled(Object)而不是onPostExecute(Object)。为了确保尽快取消任务,如果可能的话(例如在循环内),应始终定期从doInBackground(Object [])检查isCancelled()的返回值。
在文档中查看更多信息:http://developer.android.com/reference/android/os/AsyncTask.html
您可以使用此代码。我正在下载OTA文件,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 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; } } |
因此,如果要取消,只需使用以下代码:
1 | fDownload.cancel(true); |
您最好使用vogella asyncTask库,该库具有很多功能,例如优先级和取消后台任务。一个很棒的教程或使用它在这里
我从过去的两个星期开始进行研究,但我不知道我们如何手动终止Async操作。一些开发人员使用BREAK;在检查循环时。但是在我的情况下,我没有使用后台线程内部的循环。
但是我必须知道它如何唤醒其愚蠢的逻辑,但工作得很好。
1 | downloadFile.cancel(true); //This code wont work in any case. |
无需取消并在后台线程上做很多工作,而是以编程方式关闭wifi
1 2 | WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(false); |
您想在哪里终止该操作并在需要的地方打开它。
1 2 | WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(true); |
发生的情况是您的try块跳入IOException杀死了后台任务。
我已经在TextView onclick的活动中成功使用了...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //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) { } |
并在我的onCreate()中...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //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(); } }); |
和我的XML TextView元素...
1 2 3 4 5 6 7 | <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"/> |