Memory leaks and solutions are common in five Android development processes.
An object in android is no longer needed, but other objects still hold his reference, so that he cannot recycle it. As a result, this object is saved in the memory, so that memory leakage occurs. Memory leakage occurs too much, which means the application occupies too much memory. When the memory occupied exceeds the memory capacity allocated by the system, the application Crash may be caused by memory overflow. after understanding the cause and impact of Memory leakage, We need to master common memory leaks and avoid them in future Android program development. I have collected 5 common memory leakage problems and solutions for Android development. Let's take a look. 1. Memory leakage caused by a singleton. However, the static feature of the singleton mode makes the lifecycle of an object as long as that of an application. This means that an object does not need to be used, and the singleton object still holds an object, then this object cannot be released, which causes memory leakage. Example: public class AppManager {private static AppManager instance; private Context context; private AppManager (Context context) {this. context = context;} public static AppManager getInstance (Context context) {if (instance! = Null) {instance = new AppManager (context) ;}return instance ;}} the singleton needs to input the Context object, so the length of the Context lifecycle is crucial: 1. input the Context of the Application: This will be fine, because the life cycle of the Singleton is as long as that of the Application; 2. input the Context of the Activity: when the Activity corresponding to this Context exits, because the Context and Activity have the same length of life (Activity indirectly inherits from Context ), therefore, when the current Activity exits, its memory will not be recycled because the singleton object holds the reference of this Activity. Therefore, the correct Singleton should be changed to the following method: public class AppManager {private static AppManager instance; private Context context; private AppManager (Context context) {this. context = context. getApplicationContext ();} public static AppManager getInstance (Context context) {if (instance! = Null) {instance = new AppManager (context);} return instance ;}} no matter what Context is passed in, the Context of the Application will be used, the lifecycle of a single instance is as long as that of an application. This prevents Memory leakage. 2. Memory leakage caused by creation of static instances in non-static internal classes sometimes we may start frequent activities. To avoid repeated creation of the same data resources, this method is used: public class MainActivity extends AppCompatActivity {private static TestResource mResource = null; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); if (mManager = null) {mManager = new TestResource ();}//...} class TestResource {//...} In this way, a non-static internal class Singleton is created inside the Activity, and the data of the Singleton is used each time the Activity is started. This avoids repeated Resource Creation, however, this method may cause memory leakage because non-static internal classes hold external class references by default, and a static instance is created using this non-static internal class, the life cycle of the instance is as long as that of the application. As a result, the static instance will always hold the reference of the Activity, and the memory resources of the Activity cannot be recycled normally. The correct method is to set the internal class as a static internal class or extract the internal class into a singleton. If you need to use Context, use ApplicationContext. Iii. Handler-caused Memory leakage The Memory leakage caused by Handler's usage should be said to be the most common. Handler should be used to handle network tasks or encapsulate some request callbacks and other APIs at ordinary times, memory leakage may occur if Handler is written incorrectly. For example: public class MainActivity extends AppCompatActivity {private Handler mHandler = new Handler () {@ Override public void handleMessage (Message msg ){//...}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. lay Out. activity_main); loadData ();} private void loadData (){//... request Message message = Message. obtain (); mHandler. sendMessage (message) ;}} this Handler creation method will cause memory leakage, because mHandler is a non-static anonymous internal class instance of Handler, so it holds reference of external class Activity, we know that the message queue is continuously polling to process messages in a loose thread. When this Activity exits, there are still unprocessed messages in the message queue or the message is being processed, the Message in the Message queue holds the reference of the mHandler instance, and the mHandler holds the reference of the Activity. As a result, the memory resources of the Activity cannot be recycled in time, leading to memory leakage. Another method is as follows: public class MainActi Extends AppCompatActivity {private MyHandler mHandler = new MyHandler (this); private TextView mTextView; private static class MyHandler extends Handler {private WeakReference <Context> reference; public MyHandler (Context context) {reference = new WeakReference <> (context) ;}@ Override public void handleMessage (Message msg) {MainActivity activity = (MainActivity) reference. get (); if (activit Y! = Null) {activity. mTextView. setText ("") ;}}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mTextView = (TextView) findViewById (R. id. textview); loadData ();} private void loadData (){//... request Message message = Message. obtain (); mHandler. sendMessage (message) ;}} creates a static internal Handler class, and then uses weak references to the objects held by Handler. In this way The Handler objects can also be recycled during recycling. This avoids Activity leakage, but there may still be messages to be processed in the message queue of The logoff thread, therefore, we should remove messages from the message queue when Destroy or Stop the Activity. The more accurate method is as follows: public class MainActivity extends AppCompatActivity {private MyHandler mHandler = new MyHandler (this ); private TextView mTextView; private static class MyHandler extends Handler {private WeakReference <Context> reference; public MyHandler (Context context) {reference = new Weak Reference <> (context) ;}@ Override public void handleMessage (Message msg) {MainActivity activity = (MainActivity) reference. get (); if (activity! = Null) {activity. mTextView. setText ("") ;}}@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mTextView = (TextView) findViewById (R. id. textview); loadData ();} private void loadData (){//... request Message message = Message. obtain (); mHandler. sendMessage (message) ;}@ Override protected void onDestroy () {sup Er. onDestroy (); mHandler. removeCallbacksAndMessages (null) ;}use mHandler. removeCallbacksAndMessages (null); remove all messages and Runnable in the message queue. Of course, you can also use mHandler. removeCallbacks (); or mHandler. removeMessages (); To remove the specified Runnable and Message. 4. Memory leakage caused by resource not being closed. for the use of resources such as BraodcastReceiver, ContentObserver, File, Cursor, Stream, and Bitmap, the resource should be closed or deregistered in time when the Activity is destroyed, otherwise, these resources will not be recycled, resulting in Memory leakage. 5. Memory leakage caused by threads is also common for threads. The following two examples may have been written by everyone like this: // ------ test1 new AsyncTask <Void, void, Void> () {@ Override protected Void doInBackground (Void... params) {SystemClock. sleep (10000); return null;} cmd.exe cute (); // ------ test2 new Thread (new Runnable () {@ Override public void run () {SystemClock. sleep (10000 );}}). the preceding asynchronous tasks and Runnable are both anonymous internal classes, so they have an implicit reference to the current Activity. If the task is not completed before the Activity is destroyed, the memory resources of the Activity cannot be recycled, resulting in Memory leakage. The correct method is to use static internal classes, as follows: static class MyAsyncTask extends AsyncTask <Void, Void, Void> {private WeakReference <Context> weakReference; public MyAsyncTask (Context context) {weakReference = new WeakReference <> (context) ;}@ Override protected Void doInBackground (Void... params) {SystemClock. sleep (10000); return null ;}@ Override protected void onPostExecute (Void aVoid) {super. onPostExecute (aVoid); MainA Ctivity activity = (MainActivity) weakReference. get (); if (activity! = Null ){//...}}} static class MyRunnable implements Runnable {@ Override public void run () {SystemClock. sleep (10000) ;}}// ------ new Thread (new MyRunnable ()). start (); new myasynctask(thisw..exe cute (); this avoids memory resource leakage of the Activity. Of course, when the Activity is destroyed, the corresponding task AsyncTask: cancel () should also be canceled (), avoid wasting resources when running tasks in the background. The above are the five common memory leaks and corresponding solutions in android programming. If you encounter the above leakage problems in programming, you may try the corresponding methods.