Monkey脚本检测内存泄漏学习小记
来源:互联网 发布:免费下载音乐的软件 编辑:程序博客网 时间:2024/06/10 13:38
转载自 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) {
-
- getMenuInflater().inflate(R.menu.menu_main, menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
-
-
-
- int id = item.getItemId();
-
-
- 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();
- }
- }
2. 编写脚本,实时监控应用内存情况:- 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
4. 通过命令获取内存快照,并且讲文件拉到本地:- 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文件,即可进行分析: