Posted By

BenClayton on 02/25/11


Tagged


Versions (?)

Android: Template for an AsyncTask (task to run in a background thread)


 / Published in: Java
 

  1. public class MyThins {
  2.  
  3. private Object[] itemsToProcess;
  4. private OnProgressListener<FilesNeedDownloadingCheckerTask> onProgressListener;
  5. private OnFinishedListener<FilesNeedDownloadingCheckerTask, Result> onFinishedListener;
  6. private FilesNeedDownloadingCheckerTask task;
  7.  
  8. public void setOnProgressListener(OnProgressListener<FilesNeedDownloadingCheckerTask> onProgressListener) {
  9. this.onProgressListener = onProgressListener;
  10. }
  11.  
  12. public void setOnFinishedListener(OnFinishedListener<FilesNeedDownloadingCheckerTask, Result> onFinishedListener) {
  13. this.onFinishedListener = onFinishedListener;
  14. }
  15.  
  16. public FilesNeedDownloadingChecker(Object[] items) {
  17. super();
  18. this.itemsToProcess = items;
  19. }
  20.  
  21. public void cancel() {
  22. if (task != null) {
  23. task.cancel(true);
  24. }
  25. }
  26.  
  27. public void runAsync() {
  28. task = new MyThingTask();
  29. task.execute(null);
  30. }
  31.  
  32. public class Result {
  33. public ArrayList<Object> results = new ArrayList<Object>();
  34. }
  35.  
  36. public class MyThingTask extends AsyncTask<Object, Integer, Result> {
  37. Result result = new Result();
  38.  
  39. @Override
  40. protected Result doInBackground(Object... params) {
  41. // do things with this.itemsToProcess..
  42. if (isCancelled()) { return null);
  43. //
  44.  
  45. return result;
  46. }
  47.  
  48. @Override
  49. protected void onProgressUpdate(Integer... values) {
  50. super.onProgressUpdate(values);
  51.  
  52. if (onProgressListener != null) {
  53. onProgressListener.onProgress(this, (double)values[0] / (double) remoteFiles.length );
  54. }
  55. }
  56.  
  57. @Override
  58. protected void onPostExecute(Result result) {
  59. super.onPostExecute(result);
  60.  
  61. if (onFinishedListener != null) {
  62. onFinishedListener.onFinished(this, result);
  63. }
  64. }
  65. }
  66. }

Report this snippet  

You need to login to post a comment.