Last active
March 11, 2018 12:09
-
-
Save crazyhitty/8921e8f38ed1348d72707198c20fb386 to your computer and use it in GitHub Desktop.
How to use AsyncTask properly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyActivity extends AppCompatActivity { | |
private DummyAsyncTask dummyAsyncTask = new DummyAsyncTask(new DummyAsyncTask.StatusCallback() { | |
@Override | |
public void progressStarted() { | |
} | |
@Override | |
public void onProgress(int progress) { | |
} | |
@Override | |
public void progressStopped() { | |
} | |
}); | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
dummyAsyncTask.execute(); | |
} | |
@Override | |
protected void onDestroy() { | |
dummyAsyncTask.cancel(true); | |
super.onDestroy(); | |
} | |
} | |
public class DummyAsyncTask extends AsyncTask<Void, Integer, Void> { | |
private StatusCallback statusCallback; | |
public DummyAsyncTask(StatusCallback statusCallback) { | |
this.statusCallback = statusCallback; | |
} | |
@Override | |
protected void onPreExecute() { | |
super.onPreExecute(); | |
statusCallback.progressStarted(); | |
} | |
@Override | |
protected Void doInBackground(Void... voids) { | |
if (isCancelled()) { | |
// Return null, if this AsyncTask was cancelled. | |
return null; | |
} | |
// Do something. | |
publishProgress(someProgressInt); | |
return null; | |
} | |
@Override | |
protected void onProgressUpdate(Integer... values) { | |
super.onProgressUpdate(values); | |
statusCallback.onProgress(values[0]); | |
} | |
@Override | |
protected void onPostExecute(Void aVoid) { | |
super.onPostExecute(aVoid); | |
statusCallback.progressStopped(); | |
} | |
public interface StatusCallback { | |
void progressStarted(); | |
void onProgress(int progress); | |
void progressStopped(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment