I have a little problem about needing Activity/Application everywhere…
More precisely I have classes defined like this:
public class MyApp extends Application {
private static Activity currentActivity;
private static MyApp instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static void setCurrentActivity(Activity activity) {
currentActivity = activity;
}
}
And I have an Extended activity like this:
public class MyActivity extends Activity {
....
@Override
public void onResume() {
super.onResume();
MyApp.setCurrentActivity(this);
}
....
@Override
public void onDestroy() {
super.onDestroy();
MyApp.setCurrentActivity(null); // for nullifying static reference
}
}
My questions are:
- Is the above code snippet fair ?
- Should I use
super.onDestroy();after theMyApp.setCurrentActivity(null);to verify that activity is not reffered and destroyed succesfully? - And most important, what about static reference instance? where can I nullify it to not prevent from GC ?
Thanks.
Nope. The biggest problem is in
MyActivity.onDestroy(). This can be called at any time when the activity is no longer in use (ie: after it has finished). If you null outcurrentActivityinonDestroy()you will not be clearing the reference toMyActivity, you will be clearing the reference to whatever activity happens to be currently active at the moment. I you really want to havecurrentActivitypoint to the current activity, the best you can do is something like this:@Override
public void onPause() {
super.onPause();
if (MyApp.getCurrentActivity() == this) {
MyApp.setCurrentActivity(null);
}
}
Also, be aware that there is a small window between
onPause()of an activity andonResume()of the next activity so that it is possible thatcurrentActivitywill be null during this time. Watch out for that!See my comment above. You cannot null out this reference in
onDestroy().You don’t need to. There is only ever one instance of
MyAppcreated and it lives for as long as your process exists. When Android doesn’t need your process anymore it just kills the process, which will clean up everything automagically.