Skip to content

Instantly share code, notes, and snippets.

@rorist
Created July 1, 2010 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rorist/459787 to your computer and use it in GitHub Desktop.
Save rorist/459787 to your computer and use it in GitHub Desktop.
How to use AsyncTask
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import java.lang.ref.WeakReference;
private class MyTask extends AsyncTask<String, Integer, Long> {
private WeakReference<Activity> mActivity;
public MyTask(Activity activity) {
mActivity = new WeakReference<Activity>(activity);
}
@Override
protected void onPreExecute() {
final Activity a = mActivity.get();
if (a != null) {
Context ctxt = a.getApplicationContext();
}
}
@Override
protected Long doInBackground(String... strings) {
return 0;
}
@Override
protected void onProgressUpdate(Integer... progress) {
}
@Override
protected void onPostExecute(Long result) {
}
@Override
protected void onCancelled() {
}
}
@EmmanuelMess
Copy link

final Activity a = mActivity.get();
if (a != null) {

Should be:

final Activity a = mActivity.get();
if (a == null)  return;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment