Android Memory leak detection Strictmode and Mat tool use

Source: Internet
Author: User

    • Strictmode description

Android 2.3 offers a debug feature called the Tough Mode (Strictmode), which Google says has benefited hundreds of of Google apps on Android. So what does it do? It will report policy violations related to threads and virtual machines. Once a policy violation has been detected, you will get a warning that it contains a stack trace showing where your app is violating the violation. You can force a warning instead of a crash (crash), or you can just count the warnings into the log for your app to continue executing. The details of the strategy are hard to determine and you can expect Google to add more strategies as it matures with Android.
There are currently 2 strategies available, the first of which is thread-dependent, and it is primarily for the main thread (or UI thread). Since it is not good to read and write disks and network access in the main thread, Google has added a strict mode (Strictmode) hook (hook) to the disk and network code. If you turn on strict mode (Strictmode) on a thread, you will get a warning when that thread is accessing the disk and network. You can choose the warning mode. Some of the violations contain user slow calls (custom slow calls so translate line?). ), disk read-write, network access. You can choose to write a warning to Logcat, display a dialog box, flash down the screen, write to the Dropbox log file, or let the app crash. The most common practice is to write logcat or let the app crash.

strictmode.setThreadPolicy  (New Strictmode  () .detectdiskreads  () .dete Ctdiskwrites  () .detectnetwork  () .P Enaltylog  () .build  ())   

The above code is an example of setting a strict mode for threading policy (Strictmode). The
Builder class makes setup simple, and the builder function defines that all policies return builder objects, so that these functions can be concatenated as above. The last call to the build () function returns an Threadpolicy object as an argument to the Setthreadpolicy () function of the Strictmode object. Note that Setthreadpolicy () is a static function, so you do not need to instantiate the Strictmode object. Internally, Setthreadpolicy () applies the policy to the current thread. If you do not specify a detection function, you can also use Detectall () instead. Penaltylog () indicates that the warning output to Logcat, you can also use other or add new penalty (penalty) functions, such as using Penaltydeath (), once the Strictmode message is written to Logcat after the application will crash.
You do not need to open the strict mode frequently (Strictmode), you can open it in the OnCreate () function of the main activity, or you can set the strict mode (Strictmode) in the OnCreate () function of the application derived class. Any code running in a thread can be set in strict mode (Strictmode), but you do only need to set it once, once enough. The
is similar to Thread policy (threadpolicy), and the strict mode (Strictmode) has a virtual machine policy (vmpolicy). A virtual machine policy (vmpolicy) can check for memory leaks, such as the end operation before closing a SQLite object, or any other similar closure of an object before it is closed. The virtual machine policy (Vmpolicy) is created by a similar builder class, as shown in the following code. Unlike thread policy (threadpolicy), Virtual machine policy (Vmpolicy) cannot provide a warning through a dialog box.

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()      .detectLeakedSqlLiteObjects()      .penaltyLog()      .penaltyDeath()      .build()); 

Because the settings occur in threads, strict mode (Strictmode) can even find violations in the control flow from one object to another. When the violation occurs, you will be surprised to notice that the code is running on the main thread, and the stack trace will help you find out how it happened. You can then debug the problem in one step, or move the code to its own background thread, or keep it in its original way. It all depends on you. Of course, you might want to turn off tough mode (Strictmode) When your program is released as a product, and you don't want it to crash in your users ' hands just for a warning.
There are two ways to turn off the harsh mode (Strictmode), the most straightforward is to remove the code, but this is not conducive to the continuous development of the product. You can usually define an application-level Boolean variable to test if you need to invoke the harsh mode (Strictmode) code. This value is defined as false before the product is released. A more elegant approach is to define this Boolean variable in Androidmanifest.xml, using the features of debug mode. < One of the properties of the Application> field is android:debuggable, which is self-explanatory.

if (Config. DEVELOPER_mode && Build. VERSION. SDK_int >= Build. VERSION_codes. Gingerbread) {Strictmode. Setthreadpolicy(New Strictmode. Threadpolicy. Builder(). Detectall(). Detectcustomslowcalls(). Detectdiskreads(). Detectdiskwrites(). Detectnetwork(). Penaltylog(). Build());Strictmode. Setvmpolicy(New Strictmode. Vmpolicy. Builder(). Detectall(). Detectactivityleaks()//. Detectfileuriexposure()//api18 Support. Detectleakedclosableobjects()//. Detectleakedregistrationobjects()//api16 Support. Detectleakedsqlliteobjects(). Penaltylog(). Build());}

This code is I use in the project, for everyone's reference.
With the Eclipse debugging environment, ADT automatically sets the Debuggable property for you, making the project easier to manage. When you deploy the app on the emulator or directly on the device, the Debuggable property is true, and ADT sets the property to False when you export the app to build a product version. Note that if you set this property value separately, ADT does not change it.

    • Mat description
      Dalvik Debug Monitor Server (DDMS) is part of the ADT plug-in, where two features are available for memory checking:

· Heap view the allocation of heaps

· Allocation Tracker tracking Memory allocations

DDMS These two features help to find the operational behavior of a memory leak.

Eclipse Memory analysis Tools (MAT) is a professional tool for analyzing Java heap data that can be used to locate the cause of a memory leak.

Tool Address: https://www.eclipse.org/mat/

Open the Web page, as shown below:

Click in the Circle section of the diagram:

The Update Site section is.
Copy it down, open eclipse,help-install new software, interface:

Then it is the path next installation can be, may delay a little bit of time, a little slow. After the installation is successful, you need to restart Eclipse and reboot.

    • Tools and Code Usage

The above is set up from two aspects of code and tools, the following is how to use the above two points for memory leak detection. But to tell the truth, I did not use the very skilled, but in the process of doing the project, groping out a little bit of conversation, let's share here. Later, if there is a new understanding in this respect, later, and then to share with you.

When I use the code and tools above, I find that the console often outputs a bit of information:

That is, an activity was created two instances, but the activity should be created an instance, which is caused by the activity is not released in a timely manner, if the situation is serious, it will inevitably cause memory not enough app crashes.
Later on the Internet, we know that the instances=2 is the basic normal phenomenon, that is, you just opened a activity closed after the activity, the previous activity instances have not been recovered, So the output information of the above Strictmode appears.
Then there is a problem, if the instances is more than 2 of the value? Each open the same activity after the continuous open, instances value continues to increase again, that is problematic! Indicates that an object in the activity class has been holding the activity instance without releasing it, so it is time to check the code in the activity!

The above is Strictmode console information, so how to use the mat tool?
Then go to the DDMS management interface,

, find the device, open the Debug app, and in the thread of the heart, find the corresponding app process, figure:

Click the Update heap on the toolbar to update the statistics
DDMS can dump the current memory into a hprof format file, MAT read this file will give easy to read information, with its search, contrast function, you can locate the cause of memory leaks.

· Get hprof file
Click the button on the toolbar to save the memory information as a file. If the dump file is obtained using the MAT Eclipse plugin, then no conversion is required, and ADT will automatically convert and open.

· Convert hprof Files
DDMS Dump files are converted to be recognized by the mat, and the Android SDK provides the tool Hprof-conv (located under Sdk/tools)

./hprof-conv xxx-a.hprof xxx-b.hprof

· Open the converted Hprof file with the mat

Click Finish and the following screen appears:

Click on the icon in the circle in the diagram, the Histogram interface appears, open:

For example:

Where the objects is the number of objects that should be, the shallow heap amounts to the size of the memory. By using regular expressions to find the instantiation of one or more of the objects we need to judge, it is easy to find which objects are not freed.

    • Recommended

Here is a reference page: http://www.cnblogs.com/0616–ataozhijia/p/3954423.html This article is written in very clear detail.

The article points out that the cause analysis of memory leak
summed up only one: there are invalid references!
Good module design and reasonable use of design patterns help to solve this problem.

This reason is deeply agreed. The problem with my project is that this is the reason to solve it.

Http://www.blogjava.net/rosen/archive/2010/05/21/321575.html
Http://www.blogjava.net/rosen/archive/2010/06/13/323522.html
These two articles explain very in-depth, recommend to everyone.

Finally give you some tips for Android development:
Use android:largeheap= "true" tag (API level >= 11)
Declared in the application node in Androidmanifest.xml to allocate to a larger heap memory, android:largeheap tag
There are also a wide range of applications in Android applications, such as Launcher, browser, which are used on a large memory network.

1, try not to keep the activity reference for a long time.
2, try to use application context to replace the context of activity. Because application is present in the entire life cycle of the program, it is not likely to be destroyed at any time as activity.
3. Avoid using static internal classes by statically holding member variables that are referenced by activity.
4, appropriate use of weak references.
5. If you do need to maintain a reference to the activity, you must ensure that the reference is canceled before the activity's life cycle ends.

The key point is that there is no invalid reference .

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Memory leak detection Strictmode and Mat tool use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.