转载自 http://blog.csdn.net/swordgirl2011/article/details/50934413
安静的偏执的专栏
1. 编写一个带有内存泄漏问题的安卓工程
1.1 布局文件:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin"
- tools:context=".MainActivity">
- <TextView
- android:text="@string/hello_leak"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Start"
- android:id="@+id/startBtn"
- android:layout_centerVertical="true"
- android:layout_centerHorizontal="true"/>
- </RelativeLayout>
1.2 MainActivity代码:
- package com.test.tommyxie.leakcanary;
- import android.os.Bundle;
- import android.os.SystemClock;
- import android.support.v7.app.AppCompatActivity;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.Button;
- public class MainActivity extends AppCompatActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button button = (Button)findViewById(R.id.startBtn);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- start();
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- //noinspection SimplifiableIfStatement
- if (id == R.id.action_settings) {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- public void start(){
- new Thread(new Runnable() {
- @Override
- public void run() {
- SystemClock.sleep(20000);
- }
- }).start();
- }
- }
- adb shell dumpsys meminfo com.test.tommyxie.leakcanary |grep Pss
- while true
- do
- adb shell dumpsys meminfo com.test.tommyxie.leakcanary |grep TOTAL
- sleep 3
- done
3. 运行monkey命令,旋转屏幕,引发内存泄漏:
- monkey -p com.test.tommyxie.leakcanary --pct-rotation 100 -v -v 10
- adb shell am dumpheap com.test.tommyxie.leakcanary /sdcard/leak.hprof
- adb pull /sdcard/leak.hprof
5. 通过 hprof-conv 转换hprof为MAT工具可分析的格式:
- hprof-conv leak.hprof new.hprof
6. 使用MAT工具打开转换后的hprof文件,即可进行分析: