SoFunction
Updated on 2025-03-11

Android frame rate monitoring and optimization skills

What is frame rate

Frame rate refers to the number of image frames that an application can render within one second. UsuallyFPS(Frames Per Second) indicates. For example, if an application renders 60 frames per second, its frame rate is 60 FPS. The higher the frame rate, the smoother the user experience, but the stability of the frame rate is equally important.

Why frame rate is important

In user experience, the level of frame rate is directly related to the application's response speed and visual effect. However, not only should we pursue higher frame rates, but we also need to pay attention to the stability of frame rates. Below we will discuss the importance of these two aspects in detail.

Absolute value of frame rate

The absolute value of the frame rate indicates the number of image frames that the application can render within one second. Higher frame rates are often associated with smoother user experience. Why has 60 FPS become a standard? This is because the visual characteristics of the human eye are related to the refresh frequency of the electronic screen. Most phones and computer screens have a refresh rate of 60 Hz, meaning they refresh content on the screen at a frequency of 60 times per second. Therefore, when the application is able to render images at 60 FPS, it perfectly matches the refresh frequency of the screen and users will feel a very smooth experience.

If the frame rate is below 60 FPS, users may start to feel stuck or not smooth as the app cannot keep up with the refresh rate of the screen, resulting in not being smooth enough for animation and interaction. Therefore, the goal of 60 FPS is to achieve the best user experience.

Frame rate stability

The stability of the frame rate indicates how much the frame rate fluctuates over a period of time. Even if the absolute value of the frame rate is low, the user experience may still be good if it is very stable. Conversely, even if the absolute value of the frame rate is high, the user may feel uncomfortable if it is unstable. Unstable frame rates may be manifested as picture jitter or sudden frame rate drops, which may cause users to feel stuck.

Overall, the ideal situation is that the absolute value of the frame rate is high and stable. However, in some cases, the stability of the frame rate may be more important if you have to choose. For example, in virtual reality (VR) applications, a stable frame rate is essential to prevent dizziness and discomfort. In ordinary applications, even if the absolute value of the frame rate is not very high, users may feel smoother if they can remain stable.

How to monitor frame rate through code

Frame rate monitoring usually requires inserting codes in a specific part of the application to capture frame rate information. Here is an example using Android's Choreographer class to monitor frame rates:

public class FrameRateMonitor {
    private static final String TAG = "FrameRateMonitor";
    private static final long MONITOR_INTERVAL = 1000;
    private static long lastFrameTimeNanos = 0;
    private static long frameCount = 0;
    private static long monitoringStartTime = 0;
    private static  frameCallback;

    public static void startMonitoring() {
        monitoringStartTime = ();
        frameCallback = new () {
            @Override
            public void doFrame(long frameTimeNanos) {
                long currentFrameTimeNanos = frameTimeNanos;
                if (lastFrameTimeNanos != 0) {
                    long frameTimeMillis = (currentFrameTimeNanos - lastFrameTimeNanos) / 1000000;
                    float frameRate = 1000f / frameTimeMillis;
                    frameCount++;

                    long elapsedTime = () - monitoringStartTime;

                    if (elapsedTime >= MONITOR_INTERVAL) {
                        float averageFrameRate = (frameCount / (elapsedTime / 1000f));
                        (TAG, "Average Frame Rate in the last minute: " + averageFrameRate + " FPS");
                        frameCount = 0;
                        monitoringStartTime = ();
                    }
                }
                lastFrameTimeNanos = currentFrameTimeNanos;
                ().postFrameCallback(frameCallback);
            }
        };
        ().postFrameCallback(frameCallback);
    }

    public static void stopMonitoring() {
        if (frameCallback != null) {
            ().removeFrameCallback(frameCallback);
        }
        lastFrameTimeNanos = 0;
        frameCount = 0;
        monitoringStartTime = 0;
    }
}

In the example above, we created aFrameRateMonitorclass, it usesChoreographerTo calculate the frame rate regularly. You can call it in the appropriate location of the applicationstartMonitoringMethod to start frame rate monitoring and then call it when monitoring is not requiredstopMonitoringThe method stops.

Frame rate optimization tips

Once you monitor the application's frame rate problem, the next step is optimization. Here are some common frame rate optimization tips, accompanied by more detailed examples and analysis:

Reduce view hierarchy

Reducing view hierarchy is a key way to improve frame rates by reducing the nesting of views. Nesting of views can cause more complex drawing operations, thereby reducing frame rates. Here is an example:

Poor view hierarchy

<RelativeLayout>
    <LinearLayout>
        <TextView />
        <ImageView />
    </LinearLayout>
</RelativeLayout>

In the above structure, there are multiple layers of nesting, resulting in unnecessary drawing. The optimization method is to reduce nesting, as shown below:

Optimized view hierarchy

<>
    <TextView />
    <ImageView />
</>

By reducing nesting, the drawing burden can be reduced and the frame rate can be increased.

Using hardware acceleration

Android provides hardware acceleration to accelerate graphics rendering. To ensure that your application takes full advantage of hardware acceleration, you can add it in the XML layout fileandroid:hardwareAccelerated="true"Or enable hardware acceleration in your code. Here is an example:

&lt;application android:hardwareAccelerated="true"&gt;
    &lt;!-- Other configurations of the application --&gt;
&lt;/application&gt;

Enable hardware acceleration can accelerate view drawing and increase frame rate.

Asynchronous tasks

Put time-consuming tasks on the background thread to avoid the main thread being blocked, resulting in a decrease in frame rate. This includes network requests, file reading and writing, database operations, etc. Here is an example of using asynchronous tasks to handle network requests:

import 
import 
import 

class MyViewModel : ViewModel() {

    fun performNetworkRequest() {
         {
            try {
                val result = fetchDataFromNetwork()
                // Process network request results            } catch (e: Exception) {
                // Handle exceptions            }
        }
    }

    private suspend fun fetchDataFromNetwork(): String {
        // Simulate network requests        (1000) // 1 second delay, the simulated network request time        return "Network Data"
    }
}

By executing network requests in the background thread, the main thread can be prevented from being blocked and the frame rate is kept stable.

Image and animation optimization

It is very important to optimize image and animation resources in your application. You should make sure that the image is compressed and properly scaled to reduce its file size. In addition, using Vector Drawables ensures that the icons have good quality at various screen densities. Here is an example using a vector graphic as an icon:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_vector_icon" />

Using vector graphics can reduce the size of image resources and improve drawing efficiency.

Memory management

Rationally managing memory is crucial to maintaining a stable frame rate. Memory leaks and frequent garbage collection can lead to performance degradation. Make sure to release references on unused objects in a timely manner and use memory analysis tools to detect potential memory leaks. Here is an example of manually releasing object references that are no longer needed:

public class MyActivity extends Activity {
    private Bitmap largeBitmap; // Objects that need to be released
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        // Initialize largeBitmap    }

    @Override
    protected void onDestroy() {
        ();
        // Release object reference when destroying activity        if (largeBitmap != null) {
            ();
            largeBitmap = null;
        }
    }
}

By releasing object references in time, memory usage can be reduced and frame rate can be improved.

Draw with GPU

Try to use the GPU for drawing operations, which is more efficient than the CPU. You can use OpenGL ES or AndroidSurfaceViewPerform GPU-accelerated drawing. Here is an example of rendering graphics using OpenGL ES:

public class MyGLRenderer implements  {
    @Override
    public

 void onSurfaceCreated(GL10 gl, EGLConfig config) {
        // Initialize OpenGL environment    }

    @Override
    public void onDrawFrame(GL10 gl) {
        // Render frame    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, height) {
        // Handle view size changes    }
}

By drawing using GPU, graphics rendering can be accelerated and frame rate can be improved.

Case scenarios

The following are some case scenarios, providing analysis basis based on the scenarios, so that everyone can understand the solution ideas of the problem more clearly.

The frame drop rate is too high

  • The frame rate monitoring data shows that the frame rate dropped from an average of 60 FPS to 20 FPS, causing users to feel stuttering in the application.
  • CPU usage data are shown at a specific point in time, with the main thread's CPU usage reaching 90%, indicating that high CPU load is associated with lag.
  • Memory usage data shows that memory usage is increasing, suggesting that there may be a memory leak.

Stutter occurs when network requests

  • The frame rate monitoring data clearly shows that the lag problem occurs when the user makes a network request, and the frame rate drops from 60 FPS to 10 FPS.
  • CPU usage data indicate that the CPU usage of the main thread quickly rose to 100% during network requests.
  • The response time data shows that the response time of network requests is as long as more than 5 seconds, further confirming the network request problem.

Memory leaks lead to performance degradation

  • The report of the memory analysis tool clearly shows that there are memory leaks in the application, identifying specific objects and reference chains.
  • Frame rate monitoring data shows that as the memory usage continues to increase, the frame rate gradually decreases, which ultimately leads to poor user experience.

High GPU usage

  • GPU usage monitoring data show that GPU usage continues to reach 90% during graphics rendering, resulting in significant frame rate fluctuations.
  • The rendering time distribution data clearly demonstrates that the rendering time of some frames is significantly longer, which is related to high GPU usage.

Excessive battery consumption

  • Battery consumption monitoring data shows that the application continues to occupy a large amount of battery when running in the background, resulting in a significant reduction in the battery life of the device.
  • The background task execution frequency data clearly shows that some background tasks are executed too frequently and consume a lot of battery.

in conclusion

Frame rate monitoring and optimization are key steps in improving Android application performance. By using the right tools, you can better understand the application's frame rate performance, identify performance issues, and take steps to improve the user experience. Frame rate optimization requires continuous efforts, constant attention to frame rates and appropriate measures to select the appropriate frame rate range according to the nature of the application to achieve the best user experience. The absolute value and stability of the frame rate are both crucial to the user experience and should be considered and balanced.

The above is the detailed content of Android frame rate monitoring and optimization techniques. For more information about Android frame rate, please follow my other related articles!