The self-developed memory analysis tool is open source! Android Bitmap Monitor helps you locate unreasonable image usage

insert image description here

Hello everyone, I am shixin.

In our daily work, we often only pay attention to Java memory usage, mainly because there are many tools related to Java memory analysis. The difference is that there are relatively few tools for image memory analysis, and we need to spend a lot of energy when analyzing image memory problems.

We know that in the memory used by Android applications, pictures always occupy a large proportion . Take Mi 12 as an example, with a resolution of 3200 x 1440, a full-screen picture will take up at least 17MB (3200 x 1440 x 4). If there are a few more in the cache, it will basically reach hundreds of MB. A slight inappropriate loading of images may lead to a significant increase in memory overflow crashes of the application.

Therefore, we need a tool that can quickly find out whether the images loaded in the app are reasonable , such as whether the size is appropriate, whether there is a leak, whether the cache is cleaned up in time, whether images that are not currently needed are loaded, and so on.

AndroidBitmapMonitor is born for this! It is an open source Android image memory analysis tool, which can help developers quickly find out whether the image usage of the application is reasonable, and supports offline and online use .

AndroidBitmapMonitor provides these functions:

  1. Get the number of Bitmaps in memory and occupy memory
  2. View Bitmap to create stacks and threads
  3. Export Bitmap pictures to help directly locate the business to which the problem belongs
  4. Dynamic switch, can start and end at any time

Features

  • Support Android 4.4 - 13 (API level 19 - 33)
  • Support armeabi-v7a and arm64-v8a
  • Support offline real-time viewing of picture memory status and online data statistics

Functions that can be provided:

  1. Get the number of pictures in memory and occupy memory
  2. Get Bitmap to create stack and thread
  3. The full version of Bitmap Preview can be used to locate the business that the picture belongs to when the problem cannot be seen in the stack

GIF:

Screenshot of core functions:

You can view the picture memory in real time in the floating window

Image information in memory

specific information about a picture

Documentation

There are four main steps:

  1. Add gradle dependencies
  2. Initial configuration
  3. Call start and stop when needed
  4. retrieve data

1. Add dependencies in build.gradle

Android Bitmap Monitor is published on mavenCentral, so you first need to make sure your project uses mavenCentral as a warehouse.

You can add the following code in build.gradle or setting.gradle in the root directory:

allprojects {
    repositories {
        //...
        //添加 mavenCentral 依赖
        mavenCentral()
    }
}

Then add dependencies in the build.gradle file of the specific business:

android {
    packagingOptions {
        pickFirst 'lib/*/libshadowhook.so'
    }
}

dependencies {
    implementation 'io.github.shixinzhang:android-bitmap-monitor:1.0.7'
}

pickFirst 'lib/*/libshadowhook.so'Please note: In order to avoid conflicts with other libraries, it is necessary in the above packagingOptions .

After adding dependencies and executing gradle sync, the next step is to initialize and start in the code.

2. Initialization

The API that needs to be called for initialization is BitmapMonitor.init:

        long checkInterval = 10;
        long threshold = 100 * 1024;
        long restoreImageThreshold = 100 * 1024;;
        String dir = this.getExternalFilesDir("bitmap_monitor").getAbsolutePath();

        BitmapMonitor.Config config = new BitmapMonitor.Config.Builder()
                .checkRecycleInterval(checkInterval)    //检查图片是否被回收的间隔,单位:秒 (建议不要太频繁,默认 5秒)
                .getStackThreshold(threshold)           //获取堆栈的阈值,当一张图片占据的内存超过这个数值后就会去抓栈
                .restoreImageThreshold(restoreImageThreshold)   //还原图片的阈值,当一张图占据的内存超过这个数值后,就会还原出一张原始图片
                .restoreImageDirectory(dir)             //保存还原后图片的目录
                .showFloatWindow(true)                  //是否展示悬浮窗,可实时查看内存大小(建议只在 debug 环境打开)
                .isDebug(true)
                .context(this)
                .build();
        BitmapMonitor.init(config);

When showFloatWindow is true, you need to grant floating window permission when starting the app for the first time.

3. Start and stop monitoring

After the initialization is complete, you can call start/stop at any time to start and stop monitoring:

        //开启监控,方式1
        BitmapMonitor.start();
        
        //开启方式2,提供页面获取接口,建议使用
        BitmapMonitor.start(new BitmapMonitor.CurrentSceneProvider() {
            @Override
            public String getCurrentScene() {
                //返回当前顶部页面名称
                if (sCurrentActivity != null) {
                    return sCurrentActivity.getClass().getSimpleName();
                }
                return null;
            }
        });
        
        //停止监控
        BitmapMonitor.stop();

In the above code, the parameter of opening mode 2 is used to obtain the page name when the image was created. This interface can help to know which page the large image was created on. If you do not want to provide this interface, you can use the opening method 1.

So what should we use to enable monitoring?

Generally, there are two ways to use it: "Global activation" and "By business activation":

  1. Globally enabled: start as soon as it is started, used to understand the image memory data during the entire APP use process
  2. Start by business: start before entering a certain business, stop after exiting, used to understand the image memory data of a specific business

4. Get data

After the initialization is complete and the monitoring is turned on, we can intercept the creation process of each picture.

Android Bitmap Monitor provides two APIs for obtaining image data in memory:

  1. Timing callback addListener
  2. Actively obtain data dumpBitmapInfo

Timing callback refers to registering a listener. The callback of this interface will be called according to a certain time interval, which can be used for real-time monitoring :

        BitmapMonitor.addListener(new BitmapMonitor.BitmapInfoListener() {
            @Override
            public void onBitmapInfoChanged(final BitmapMonitorData data) {
                Log.d("bitmapmonitor", "onBitmapInfoChanged: " + data);
            }
        });

The interval time is the parameter checkRecycleInterval passed during initialization, and the returned data structure is as follows:

public class BitmapMonitorData {
    //历史创建的总图片数
    public long createBitmapCount;
    //历史创建的总图片内存大小,单位 byte
    public long createBitmapMemorySize;

    //当前内存中还未回收的图片数
    public long remainBitmapCount;
    //当前内存中还未回收的图片内存大小,单位 byte
    public long remainBitmapMemorySize;

    //泄漏(未释放)的 bitmap 数据
    public BitmapRecord[] remainBitmapRecords;
    
    //...
}

Actively obtain data refers to actively calling to BitmapMonitor.dumpBitmapInfo()obtain all the data in the memory, which can be used to report data when the memory increases :

        //获取所有数据
        BitmapMonitorData bitmapAllData = BitmapMonitor.dumpBitmapInfo();
        Log.d("bitmapmonitor", "bitmapAllData: " + bitmapAllData);
        
        //仅获取数量和内存大小,不获取具体图片信息
        BitmapMonitorData bitmapCountData = BitmapMonitor.dumpBitmapCount();
        Log.d("bitmapmonitor", "bitmapCountData: " + bitmapCountData);

dumpBitmapInfoIt will return the information of all pictures in the memory. If you only want to get the total number of pictures and the total amount of memory, you can call it dumpBitmapCount, which is faster and lighter.

Summarize

This article introduces the functions and core API of Android Bitmap Monitor , the latest open source image memory analysis tool . You can see that it provides a lot of image information. What can we use it for?

Currently think of these usage scenarios:

  1. Large image alarm: Once an image that is too large is loaded online, a log can be reported to notify the developer to check
  2. Image leak monitoring: After the page exits, the image memory does not drop, you can check what image leaked and where the code caused it
  3. Repeated loading of pictures: the same picture is decoded multiple times, which does not make good use of the memory cache

Through this library, we can have a deeper understanding of the image usage of the APP, and can also broaden the knowledge. In the future, when we talk about memory optimization in interviews, we don’t have to worry about only talking about Java memory haha! What are you waiting for, come and use it!

If it helps you, please click a star, thanks:
https://github.com/shixinzhang/AndroidBitmapMonitor

Guess you like

Origin blog.csdn.net/u011240877/article/details/129150824