BackgroundTask.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
  2. import android.os.AsyncTask;
  3. /**
  4. * Created by Julien on 07.01.2015.
  5. */
  6. public class BackgroundTask extends AsyncTask<Void, Void, String> {
  7. public static String BACKGROUND_TASK_MESSAGE_SUCCESS = "success";
  8. /**
  9. * This listener calls didSucceed if the method performInBackground will return true, otherwise it calls didFail.
  10. */
  11. public interface BackgroundTaskCompletionListener {
  12. public void didSucceed();
  13. public void didFail(String errorMessage);
  14. }
  15. private boolean isInterrupted;
  16. private boolean wasSuccessfully;
  17. private String errorMessage;
  18. public void interrupt(boolean b){
  19. this.isInterrupted = b;
  20. }
  21. public boolean isInterrupted() {
  22. return isInterrupted;
  23. }
  24. private BackgroundTaskCompletionListener completion_listener;
  25. public BackgroundTask(BackgroundTaskCompletionListener l){
  26. super();
  27. this.completion_listener = l;
  28. }
  29. /**
  30. * Interrupts the background process.
  31. * @param isInterrupted
  32. */
  33. public void setInterrupted(boolean isInterrupted) {
  34. this.isInterrupted = isInterrupted;
  35. }
  36. /**
  37. * Do any stuff here if it should run in the background. It should return true or false if the process was successfully.
  38. * @return String error message, default is BACKGROUND_TASK_MESSAGE_SUCCESS
  39. */
  40. public String performInBackground(){
  41. return BACKGROUND_TASK_MESSAGE_SUCCESS;
  42. }
  43. @Override
  44. protected String doInBackground(Void... params) {
  45. String message = this.performInBackground();
  46. if (message == null || message.equals(BACKGROUND_TASK_MESSAGE_SUCCESS)){
  47. this.wasSuccessfully = true;
  48. } else{
  49. this.wasSuccessfully = false;
  50. }
  51. this.errorMessage = message;
  52. return message;
  53. }
  54. /*
  55. * (non-Javadoc)
  56. * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
  57. */
  58. @Override
  59. protected void onPostExecute(String result) {
  60. if (this.completion_listener != null) {
  61. if (this.wasSuccessfully) {
  62. this.completion_listener.didSucceed();
  63. }else {
  64. this.completion_listener.didFail(this.errorMessage);
  65. }
  66. }
  67. }
  68. /*
  69. * (non-Javadoc)
  70. * @see android.os.AsyncTask#onPreExecute()
  71. */
  72. @Override
  73. protected void onPreExecute() {
  74. }
  75. }