What I'm trying to achieve:
- Reduce the use of memory that is no longer displayed on the screen, i.e. another action was launched.
- The possibility for this action is still on the navigation stack, so I assume that I will have to rebuild what was destroyed in onStop into onStart, but I'm not sure how to do it when all the views / buttons were built using layout. xml.
Situation:
I have an Android app that is very heavy, but these images are static in many layouts, with the same backgrounds, button images, navigator headers, etc. This led me to easily create layouts without touching too much code, indicating all the images, their attributes and src positions in the layout.xml files. And it worked great, it was easy to get up and work, but now there are many reports of power shutdown due to excessive memory usage.
So, trying to clean up and allow gc to remove images and views that are not on the screen, I came across an article (see the bottom of the question) suggesting inside the onDestroy method, capturing the trick of your root element within the layout and recursively navigating through the tree, deleting representations and detaching them. However, this only works and is not guaranteed in accordance with the documents when pressing the return buttons.
So onDestroy does not help me when I push a new activity on the stack and do not clear what just left the screen. But the plus side of using the onDestroy method is that the starting point starts with onCreate, so all views are created correctly. When I use this method in onStop, the memory is cleared beautifully when I start a new action, but because I published all the views and they were built using layout.xml, I don’t understand how or what I need to rebuild on onStart. if I destroy everything in onStop, especially considering that I never created any views in the code, since they were all configured due to layout.xml files.
Key questions: How to clear memory when starting a new action? If the contexts are handled correctly, is this consistent with the fact that gc will still clear all image views that are off-screen and rebuild them automatically?
Is there any way to use this inside 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(); } }