Skip to content

Instantly share code, notes, and snippets.

@crazyhitty
Last active March 11, 2018 12:09
Show Gist options
  • Save crazyhitty/8921e8f38ed1348d72707198c20fb386 to your computer and use it in GitHub Desktop.
Save crazyhitty/8921e8f38ed1348d72707198c20fb386 to your computer and use it in GitHub Desktop.
How to use AsyncTask properly
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