First, the memory mechanism of Android
Android programs are written in the Java language, so Android's memory management is similar to Java's memory management. The programmer allocates memory for the object through new, and all objects allocate space within the Java heap, while the object's release is done by the garbage collector. C + + memory mechanism is "who pollution, who governance", Java is more humane, give us a dedicated cleaner (GC).
So how can a GC confirm that an object has been discarded? Java uses the principle of a forward graph. Java considers the reference relationship as a directed edge of the graph, and has a pointing edge from the referrer to the Reference object. The thread object can serve as the starting vertex of a forward graph, which is a tree starting from the starting vertex, the objects that the root vertices can reach are valid objects, and the GC does not reclaim those objects. If an object (connected sub-graph) and this root vertex are unreachable (note that the graph is a forward graph), then we think that this (these) objects are no longer referenced and can be recycled by GC.
Second, the memory overflow of Android
How does the memory overflow of Android occur?
Android virtual machine is a register-based Dalvik, its maximum heap size is generally 16M, and some machines are 24M. So the amount of memory space we can use is limited. OutOfMemory errors occur if our memory footprint exceeds a certain level.
Why is there a situation where memory is not enough? I think there are two main reasons:
- Due to our program errors, long-term maintenance of certain resources (such as the context) of the reference, resulting in memory leaks, resources caused by the failure to release.
- Multiple objects that consume too much memory (such as bitmap) are saved, causing memory to exceed the limit.
Three, the evil of the static
Static is a keyword in Java that, when used to decorate a member variable, belongs to that class, not an instance of that class. So with the static modified variable, its life cycle is very long, if it is used to reference some resources to consume too many instances (the context of the most cases), then it should be treated with caution.
Public class ClassName { privatestatic Context mcontext; // omitted }
The code above is dangerous, if the activity is assigned to Mcontext. So even if the activity is OnDestroy, the activity will not be released because there is still a reference to the object that holds it.
We'll give you an example of an Android document.
private static drawable Sbackground; @Override protected void OnCreate (Bundle state) { super . OnCreate (state); TextView label = new TextView (this ); Label.settext ( Leaks is bad "); if (sbackground = = null = getdrawable (R.DRAWABLE.LARGE_BITMAP); } label.setbackgrounddrawable (Sbackground); Setcontentview (label); }
Sbackground, is a static variable, but we find that we do not explicitly save the Contex reference, but when drawable is connected to the view, drawable sets the view to a callback, Because the view is a reference to the context, in fact we still have a reference to the context. This reference chain is as follows:
Drawable->textview->context
So, eventually the context was not released, and a memory leak occurred.
How can we effectively avoid the occurrence of such a reference?
First, you should avoid static member variables referencing resources that consume too many instances, such as context.
Second, the context as far as possible to use application context, because the application context of the life cycle is relatively long, reference it will not be a memory leak problem.
Third, use WeakReference instead of strong references. For example, you can use weakreference<context> mcontextref;
The details of this section can also refer to the article section of the Android documentation.
All threads are the bane of the cause.
Threads are also an important source of memory leaks. The main reason for a thread's memory leak is that the thread life cycle is not controllable. Let's consider the following section of code.
Public classMyActivityextendsActivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); NewMyThread (). Start (); } Private classMyThreadextendsthread{@Override Public voidrun () {Super. Run (); //Do somthing } } }
This code is very common and simple, it is the form that we often use. Let's think of a problem: assuming that the mythread run function is a time-consuming operation, when we turn on the thread, we turn the device's horizontal screen into a vertical screen, and normally the activity is recreated when the screen is converted, as we thought, the old activity should be destroyed. However, this is not the case in fact.
Since our thread is the inner class of activity, a reference to activity is saved in Mythread, and when Mythread's run function does not end, Mythread is not destroyed, so the old activity it references is not destroyed. Therefore, there is a memory leak problem.
Some people like to use Android-provided asynctask, but in fact the asynctask problem is even more serious, and thread only has this memory leak problem when the run function does not end. However, the implementation mechanism within the asynctask is the use of threadpoolexcutor, the life cycle of the thread object produced by this class is indeterminate and is beyond the control of the application, so if Asynctask is the inner class of activity, The problem of memory leaks is more likely.
How should the memory leak problem caused by this thread be resolved?
First, the internal class of the thread is changed to a static inner class.
Second, use weak references inside the thread to save the context reference.
The model is resolved as follows:
Public Abstract classWeakasynctask<params, Progress, Result, weaktarget>extendsAsynctask<params, Progress, result> { protectedWeakreference<weaktarget>Mtarget; PublicWeakasynctask (weaktarget target) {mtarget=NewWeakreference<weaktarget>(target); } /** {@inheritDoc} */@Overrideprotected Final voidOnPreExecute () {FinalWeaktarget target =Mtarget.get (); if(Target! =NULL) { This. OnPreExecute (target); } } /** {@inheritDoc} */@Overrideprotected FinalResult doinbackground (params ... params) {FinalWeaktarget target =Mtarget.get (); if(Target! =NULL) { return This. Doinbackground (target, params); } Else { return NULL; } } /** {@inheritDoc} */@Overrideprotected Final voidOnPostExecute (Result result) {FinalWeaktarget target =Mtarget.get (); if(Target! =NULL) { This. OnPostExecute (target, result); } } protected voidOnPreExecute (weaktarget target) {//No Default Action } protected AbstractResult Doinbackground (weaktarget target, params ... params); protected voidOnPostExecute (weaktarget target, result result) {//No Default Action } }
In fact, threading problems are not just memory leaks, but they can also lead to catastrophic problems. Because this article discusses memory issues, there is no discussion here.
Five, super Big Fat bitmap
It can be said that the majority of people who appear outofmemory problems are because of bitmap problems. Because bitmap occupies too much memory, it is a "super fat", especially the resolution of large pictures, if you want to display more than the problem is more significant.
How to solve the memory problem that bitmap brings to us?
First, the timely destruction.
Although the system is able to confirm that the memory allocated by bitmap will eventually be destroyed, it is likely to exceed the Java heap limit because it consumes too much memory. Therefore, in the use of bitmap, should be timely recycle off. Recycle is not sure that the bitmap will be released immediately, but will give the virtual machine a hint: "The picture can be released."
Second, set a certain sampling rate.
Sometimes, we want to show the area is very small, there is no need to load the entire picture, and only need to record a reduced image, when you can set a certain sampling rate, then you can greatly reduce the memory occupied. As in the following code:
Private ImageView preview; New bitmapfactory.options (); = 2; // The image width is the original One-second, that is, the picture is the original One-fourth NULL , options);
Third, clever use of soft references (softrefrence)
Sometimes we don't keep a reference to it after we use bitmap, so we can't call the Recycle function. By using soft references skillfully, the bitmap can be effectively released when the memory is not fast enough. The following example:
/**This example is for bloggers to write, to illustrate usage, not to verify*/ Private classMyadapterextendsBaseadapter {PrivateArraylist<softreference<bitmap>> mbitmaprefs =NewArraylist<softreference<bitmap>>(); PrivateArraylist<value>mvalues; PrivateContext Mcontext; PrivateLayoutinflater Minflater; Myadapter (context context, ArrayList<Value>values) {Mcontext=context; Mvalues=values; Minflater=(Layoutinflater) Context.getsystemservice (Context.layout_inflater_service); } Public intGetCount () {returnmvalues.size (); } PublicObject GetItem (inti) {returnMvalues.get (i); } Public LongGetitemid (inti) {returni; } PublicView GetView (intI, view view, ViewGroup ViewGroup) {View Newview=NULL; if(View! =NULL) {Newview=view; } Else{Newview= (View) minflater.inflate (R.layout.image_view,false); } Bitmap Bitmap=Bitmapfactory.decodefile (Mvalues.get (i). FileName); Mbitmaprefs.add (NewSoftreference<bitmap> (Bitmap));//add ArrayList here((ImageView) newview). Setimagebitmap (bitmap); returnNewview; } }
Six, the whereabouts of the strange cursor
The cursor is a class that manages the collection of data after the Android query data, and under normal circumstances there is no memory problem if the query gets a small amount of data, and the virtual machine can guarantee that the Cusor will eventually be released.
However, if the cursor has a large data volume, especially if there is blob information in it, it should be ensured that the memory occupied by the cursor is released in a timely manner rather than waiting for the GC to handle it. And Android is obviously prone to the programmer manually close the cursor, because in the source code we find that if we wait for the garbage collector to recycle, the user will be given an error.
So the way we use the cursor is generally as follows:
cursor cursor =NULL; Try{cursor= Mcontext.getcontentresolver (). Query (URI,NULL,NULL,NULL,NULL); if(Cursor! =NULL) {Cursor.movetofirst (); //Do something } } Catch(Exception e) {e.printstacktrace (); } finally { if(Cursor! =NULL) {cursor.close (); } }
In one case, we can't just close the cursor, which is the case in CursorAdapter, but notice that CursorAdapter does not automatically close the cursor at the end of the acivity, so You need to close it manually in the OnDestroy function.
@Override protected void OnDestroy () { ifnullnull) { madapter.getcursor (). Close (); Super. OnDestroy (); }
The Changecursor function in CursorAdapter will release the original cursor and replace it with the new cursor, so you don't have to worry about the original cursor being closed.
You might think of using activity's managedquery to generate the cursor, so that the cursor will coincide with the acitivity's life cycle, and what a perfect solution! In fact, however, Managedquery also has a lot of limitations.
The cursor generated by managedquery must be guaranteed not to be replaced, because many programs may actually be uncertain about the query condition, so we often replace the cursor with the cursor of the new query. Therefore, the application of this method is also very small.
Seven, the other to say.
In fact, to reduce the use of memory, in fact there are many ways and requirements. For example, do not use the entire picture, try to use 9path images. Adapter to use Convertview and so on, a lot of details can save memory. These all need us to dig, who call Android's memory not to force again.
Android, who moved my memory