Android solves memory overflow and android memory overflow.
00:03:57 tags: Memory leakage android OutOfMemory Bitmap Cursor copyright statement: original works, declined to reprint! Otherwise, legal liability will be held. I. Android memory mechanism Android programs are written in Java, so the memory management of Android is similar to that of Java. The programmer allocates memory for the object through new, and all objects are allocated space in the java heap. However, the release of the object is done by the garbage collector. In C/C ++, the memory mechanism is "Who is polluted and who is responsible for governance". java is more user-friendly and a dedicated garbage collector (GC) is invited for us ). How can GC check whether an object has been deprecated? Java adopts the principle of Directed Graphs. Java considers the reference relationship as directed edges of a graph, and directed the directed edge from the quotor to the referenced object. A thread object can be used as the starting vertex of a directed graph. This graph is a tree starting from the starting vertex. All objects that can be reached by the root vertex are valid objects and GC will not recycle these objects. If an object (connected subgraph) is inaccessible to this root vertex (note that this graph is a directed graph), we think this (these) object is no longer referenced and can be recycled by GC. 2. How does Android memory overflow occur? The Android virtual machine is a register-based Dalvik. Its maximum heap size is generally 16 M, and some machines are 24 M. Therefore, the memory space we can use is limited. If our memory usage exceeds a certain level, an OutOfMemory error occurs. Why is memory insufficient? I think there are two main reasons: Due to program errors, some resources (such as Context) can be referenced for a long time, causing memory leakage and resources cannot be released. Saves multiple objects (such as Bitmap) that consume too much memory, resulting in memory exceeding the limit. 3. The evil static is a keyword in Java. When it is used to modify a member variable, the variable belongs to the class, not the instance of the class. Therefore, the life cycle of a variable modified with static is very long. If you use it to reference some instances that consume too much resources (the case of Context is the most), you should be cautious. Public class ClassName {private static Context mContext; // omitting} is dangerous. If you assign an Activity value to mContext. Even if the Activity has been onDestroy, the Activity will not be released because there are still objects that store its reference. Let's take an example in the Android document. Private static Drawable sBackground; @ Override protected void onCreate (Bundle state) {super. onCreate (state); TextView label = new TextView (this); label. setText ("Leaks are bad"); if (sBackground = null) {sBackground = getDrawable (R. drawable. large_bitmap);} label. setBackgroundDrawable (sBackground); setContentView (label);} sBackground is a static variable, but we found that we did not explicitly Save the reference of Contex. However, when Drawable is connected to View, Dra Wable sets the View as a callback. Because the View contains the reference of Context, we still save the reference of Context. The reference chain is as follows: Drawable-> TextView-> Context. Therefore, the Context is not released and Memory leakage occurs. How can we effectively avoid such a reference? First, we should try our best to avoid using static member variables to reference instances that consume too much resources, such as Context. Second, use the Application Context whenever possible. Because the Application Context has a long life cycle, it will not cause memory leakage if referenced. Third, use WeakReference instead of strong reference. For example, you can use WeakReference mContextRef. For details about this part, see the Article in the Android document. 4. It is a thread fault. The thread is also an important source of Memory leakage. The main cause of thread Memory leakage is the uncontrollable thread lifecycle. Let's consider the following code. Public class MyActivity extends Activity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); new MyThread (). start ();} private class MyThread extends Thread {@ Override public void run () {super. run (); // do somthing} This code is very common and very simple. It is often used. Let's think about a problem: assume that the run function of MyThread is a very time-consuming operation. When we enable this thread, we change the horizontal screen of the device to a vertical screen, generally, when the screen is switched, the Activity will be re-created. According to our ideas, the old Activity should be destroyed. However, this is not the case. Because our thread is an internal class of Activity, a reference of Activity is saved in MyThread. When the run function of MyThread is not completed, MyThread will not be destroyed, therefore, the old Activity referenced by it will not be destroyed, so Memory leakage occurs. Some people like to use AsyncTask provided by Android, but in fact AsyncTask is more serious. This memory leakage problem occurs only when the run function does not end, however, the internal implementation mechanism of AsyncTask is to use ThreadPoolExcutor. the life cycle of the Thread object generated by this class is uncertain and cannot be controlled by the application. Therefore, if AsyncTask is used as the internal class of the Activity, it is more prone to memory leakage. How should we solve the memory leakage caused by such threads? First, change the internal class of the thread to the static internal class. Second, use weak references within the thread to save Context references. The solution model is as follows: public abstract class WeakAsyncTask extends AsyncTask {protected WeakReference mTarget; public WeakAsyncTask (WeakTarget target) {mTarget = new WeakReference (target );} /** {@ inheritDoc} */@ Override protected final void onPreExecute () {final WeakTarget target = mTarget. get (); if (target! = Null) {this. onPreExecute (target) ;}}/** {@ inheritDoc} */@ Override protected final Result doInBackground (Params... params) {final WeakTarget target = mTarget. get (); if (target! = Null) {return this. doInBackground (target, params);} else {return null ;}/ ** {@ inheritDoc} */@ Override protected final void onPostExecute (Result result Result) {final WeakTarget target = mTarget. get (); if (target! = Null) {this. onPostExecute (target, result) ;}} protected void onPreExecute (WeakTarget target) {// No default action} protected abstract Result doInBackground (WeakTarget target, Params... params); protected void onPostExecute (WeakTarget target, Result result) {// No default action} In fact, the thread issue is not only about memory leakage, but also catastrophic problems. This article does not discuss memory issues.