If you use anonymous classes, they will have an internal reference to the external class, so they donβt like that it becomes inaccessible all of a sudden because other links have been cleared. AsyncTask does not actually change anything; it uses similar mechanics to notify about the results.
You can use loaders , they are designed to synchronize with the activity life cycle. They are only available with Android 3.0, but you can use the support package to work with them on any device with 1.6 or later.
There is an even simpler solution, you can simply use a boolean field that indicates whether the activity has disappeared. You should set this field to onPause() (or when you think you will no longer need notifications) and check it when you show the toast. You donβt even have to use synchronization, since this field is limited by the main thread, so it is absolutely safe. By the way, if you change this field somewhere else than in onDestroy() , be sure to add an operator that resets your field back to the matching method.
public class MyActivity extends Activity { private boolean activityDestroyed = false; @Override protected void onDestroy() { activityDestroyed = true; } private void updateData() { new Thread() { @Override public void run() { final Data newData = requestData(); if (newData == null) return; runOnUiThread(new Runnable() { public void run() { if (activityDestroyed) return; Toast.makeText(MyActivity.this, "Blah", Toast.LENGTH_SHORT).show(); } }); } }.start(); } }
source share