What I'm trying to achieve:
- Reduce memory usage of activity that is no longer on screen, ie another activity has been started
- The ability for this activity to still be within the navigation stack, so I'm assuming I would have to re-build what was destroyed in onStop, within onStart, but not sure how to do that when all views/buttons were built using layout.xml's .
The situation:
I have an Android app that is very image heavy, but these images are static on many of layouts, with the same backgrounds, button images, nav headers etc. This led me to build the layouts quite easily without touching code too much by specifying all the imageViews, their src attributes and positions within the layout.xml files. And this worked great, was easy to get up and running, however now there are many reports of force closes due to exceeding the memory usage.
So on in an attempt to cleanup and allow gc to remove images and views that are not on screen, I came across an article (see bottom of question) suggesting within the onDestroy method, grabbing a hold of your root element within the layout and recursively going through the tree removing views and unbinding them. However this only is fired and not guaranteed according to docs when the back buttons is pressed.
So onDestroy does not help me when I am pushing a new activity onto the stack and wan't to clean up what just left the screen. But the plus side of using the onDestroy method is that the entry point begins at onCreate, so the views are all built up correctly. When I use this method within onStop, memory get's cleaned up nicely when I start a new activity, but because I've nuked all the views, and they were built using layout.xml, I don't understand how or what I need to re-build in onStart if I destroy everything in onStop especially considering I never created any views in code as they were all setup because of the layout.xml files.
Main Questions: How do I cleanup memory when I start a new Activity? If contexts are handled correctly, is it convention that gc would cleanup all the imageviews that are off screen anyway and re-build them automatically?
Can this be used somehow within onStop ?
@Override
protected void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.RootView));
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}