Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Memory leak analysis using Android studio     - CentOS Linux firewall configuration and Close (Linux)

- Neo4j map data processing tab (Database)

- Advanced Linux security settings (Linux)

- Linux Learning --- disk partition / relational representation + mount (Linux)

- MySQL5.6 based GTID master-slave replication (Database)

- Linux system last command usage (Linux)

- Oracle Shared Server Configuration (Database)

- Use 3G wireless network card under Linux (Linux)

- Using Java to build micro-services (Server)

- How to use the tab in Vim carried Python code completion (Linux)

- Linux loopback adapter Driven Design (Programming)

- How to Debian Linux the default Python version switch to alternative version (Linux)

- CentOS7 install NTFS-3G driver (Linux)

- When should I use Angular 2 (Programming)

- Open source backup software installed on Ubuntu Systemback 1.6.201 (Linux)

- apt-get and apt-cache show command examples (Linux)

- Use Visual Studio Code Development TypeScript (Linux)

- Understand the profound discussion of some of the options for wireless encryption (Linux)

- After installing minimize RHEL / CentOS 7 need to do some things (Linux)

- Linux commands with browsing and downloading files (Linux)

  Memory leak analysis using Android studio
  Add Date : 2018-11-21      
  As far Android Studio 1.3, its internal MemoryDump features are difficult to use, or the use of MAT better.

Android as a platform developed using java helped us solve many of the underlying problems, such as memory management, platform dependent, and so on. However, we often encounter problems OutOfMemoey garbage collection in the end go?

Next is a Handler Leak example, it will generally be in the compiler warnings.

Required tools

Android Studio 1.1 or higher
Eclipse MemoryAnalyzer
Sample Code

public class NonStaticNestedClassLeakActivity extends ActionBarActivity {

  TextView textView;

  public static final String TAG = NonStaticNestedClassLeakActivity.class.getSimpleName ();

  protected void onCreate (Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    setContentView (R.layout.activity_non_static_nested_class_leak);
    textView = (TextView) findViewById (R.id.textview);
    Handler handler = new Handler ();

    handler.postDelayed (new Runnable () {
      @Override Public void
        textView.setText ( "Done");
      } // A mock for long time work
    }, 800000L);

This is a very basic Activity. Note that this anonymous Runnable was sent to the Handler, and very long delays. Now we run this Activity, repeatedly rotate the screen, and then export the memory and analysis.

Memory imported into Eclipse MemoryAnalyzer

Use Androidstudio Export heap dump

Android Studio dump Memory Analyze
Click the lower left corner of Android
Select the name of your application package
Click initiates garbage collection on selected vm
Click dump java heap for selected client
Open MAT, analysis

MAT is a tool for java heap variables in the analysis, it can be used to analyze memory leaks.

Click the icon OQL
In the window, enter select * from instanceof android.app.Activity press Ctrl + F5 or! Button
A miracle happened, and now you see a lot of activity leaked
This is really quite not optimistic, we have to analyze why the GC does not reclaim it

Query in OQL (Object Query Language) input window to get all Activities in memory, this query code is not very simple and efficient it?

Click on an activity object, right-select the Path to GC roots

Message in looper hold a reference to Activity
In the new window that opens, you can find your Activity is referenced by this $ 0, it is actually an anonymous class reference to the current class. this $ 0 has been cited callback, then it is referenced Message in a bunch of next, and finally to the main thread until the end.

Under no circumstances must you create a non-static inner class in the class, inner classes will (automatically) to the current class has a strong reference.

Once you have sent to Runnable or Message Handler, which will be placed in LooperThread message queue, and held a reference until Message is processed. Send this message postDelayed, you enter the number of seconds delay, it will disclose at least the number of seconds. And send a message without delay, then, when too many messages in the queue will be adhered to as a temporary leak.

Try using static inner class to solve

Now put into the static class Runnable

Now, shake the phone, export memory

Why has emerged leaked it? Activities we take a look at the reference.

See the following references mContext yet, it is mTextView references, such instructions static inner classes is not enough, we still need to be modified.

Using weak references + static Runnable

Now we have just a memory leak culprit - TextView into weak references.

Note again that we keep the TextView is weak references, now let it run, shaking the phone

Carefully operate WeakReferences, they can always be empty before use to determine whether the air.

Wow! There is only one instance of the Activity, this time finally solved our problem.

Therefore, we should keep in mind:

Use static inner classes
Handler / Runnable depends to use weak references.
If you put the code now compared to the beginning of the code, you will find them very different from the code understandable Introduction First, you can even make out the brain operating results.

And now the code is more complex, there are a lot of template code, when postDelayed set to a short period of time, such as the case of 50ms, the code write so little loss. In fact, there is an easier way.

onDestroy manually control lifecycle

Handler can use removeCallbacksAndMessages (null), it will have to remove this Handler Runnable and Message.

// Fixed by manually control lifecycle
  @Override Protected void onDestroy () {
    super.onDestroy ();
    myHandler.removeCallbacksAndMessages (null);
Now run, rotary phones, memory export

Good! Only one instance.

Write can make your code more concise and readable. The only thing to remember is to remember that in the life cycle onDestory when manually remove all messages.

Use WeakHander

in conclusion

Use postDelayed in Handler need extra attention in order to solve the problem, we have three ways

Using static internal Handler / Runnable + weak references
In onDestory when manually remove Message
Badoo developed using third-party WeakHandler
You can choose any of these three, the second seems more reasonable, but requires extra work. The third method is my favorite, of course, you should also pay attention to the external references can not WeakHandler strong common use.
- Analyzing Linux server architecture is 32-bit / 64-bit (Server)
- Oracle 11g maintenance partitions - Adding Partitions (Database)
- Shell for loop (Programming)
- SLF4J Tutorial (Programming)
- Linux kernel compilation, the configuration of the motor drive (Programming)
- ARP spoofing prevent Linux environment LAN (Linux)
- To install the Ubuntu Touch emulator on Ubuntu (Linux)
- Export error: ORA-04063: package body dmsys dbms dm model exp has error (Database)
- Linux System Getting Started Tutorial: Five image processing software (Linux)
- Ubuntu system safe and caution sudo su command (Linux)
- To execute the cp command prompt type skip folder under CentOS (Linux)
- Java implementation chain store binary search tree (recursive method) (Programming)
- Docker: Mirroring and container operations (Server)
- Linux at command (Linux)
- Git Experience Sharing - Using a remote repository (Linux)
- Linux system security knowledge (Linux)
- Linux command execution judge sentences -;, &&, || (Linux)
- Hard disk encryption to protect data security (Linux)
- MySQL related statements (CRUD) (SQLyog software) (Database)
- Notebook computer forget password solution (Linux)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.