How to optimize the performance of Android APP?

Android performance optimization:

1. Caton optimization:

Why is it stuck: Android uses the message mechanism to update the UI thread. The UI thread has a looper. The loop method continuously takes out the message and calls the bound handler to execute it on the UI thread. If there is a time-consuming operation in the dispatchMessage method, it will cause Frames are dropped, drawing timeouts, and UI threads are blocked, resulting in stuttering. Choreographer.FrameCallBack can get the drawing time of each frame to calculate the time between two frames. If it exceeds 16ms, frame loss will occur.

Problem detection tools:

blockCanary: Detection principle: monitor the time-consuming situation of dispatchMessage function. Looper and handler handle a series of actions such as rendering.

sysTrace: command line tool

traceView: built-in tool of android sdk.

GPU overdrawing debugging mode: developer options

Solution:

Remove the unnecessary background color, flatten the number of layout views, reduce the transparent color, that is, the use of alpha, and use a lightweight system layout, such as viewstub, behavior series dialog or view,

Two , ANR optimization

ActivityManagerService (referred to as AMS ) and WindowManagerService (referred to as WMS ) will detect the response time of the App. If the App cannot respond to the screen touch or keyboard input time at a specific time, or the specific event has not been processed, an ANR will occur. Whether it is the four major components or processes, as long as ANR occurs, the AMS.appNotResponding() method will eventually be called.

Detection principle: All keyEvents and touchEvents in android are placed in the queue in an orderly manner and executed in sequence. Each executed event is saved in the waitQueue and removed from it after execution. When the user triggers an event, it will first determine whether the waitQueue is empty, and it will respond immediately if it is empty. If it is not empty, it means that there are still events that have not been executed. At this time, it will determine whether the current time and the response time of the previous event More than the timeout time (usually 5s, broadcast is 10s), if it times out, it will be prompted by the ActivityManagerService pop-up box.

the reason:

  • Main thread blocking or main thread data reading
  • CPU is fully loaded, I/O is blocked
  • Not enough storage
  • Major components ANR (service, broadCast time-consuming operation)

Testing tools and principles:

Tools: Log, traces.txt, Java thread call analysis, DDMS analysis of ANR problems,

All events (activity, service lifecycle management) in Android are processed through Looper+messageQUeue+handler. The same as the Caton principle, here is to record the execution time of each message dispatchMessage.

Solution:

Try to avoid time-consuming operations in the main thread (UI thread).
 

3. Memory optimization. 

       1) Memory jitter is caused by a large number of objects entering and leaving the newborn area in a short period of time, and it is accompanied by frequent GC

avoid:

       Try to avoid creating objects in the loop, and move the object creation outside the loop.

      Note that the onDraw() method of the custom View will be called frequently, so objects should not be created frequently in it.

      When you need to use Bitmaps a lot, try to cache them in an array for reuse.

      For objects that can be reused, you can use the object pool to cache them in the same way.

      2) Memory leak: The general memory leak (traditional memory leak) is caused by forgetting to release the allocated memory. (Cursor forgot to close etc.)

                             The reason for logical memory leak is that when the application no longer needs the object, all references to the object have not been released yet.

 Detailed explanation: After the program applies for the memory, when the memory is no longer  needed, it cannot be released & returned to the program . :

                  Should have been recycled: do not use the object

                  Cannot be recycled: other objects hold references to objects that are no longer used //

                 The essential reason: (unconsciously) the life cycle of the referrer —> when the referrer needs to be destroyed, it cannot be recycled correctly

Knowledge point: when will GC be triggered?

Garbage Collection (Garbage Collection) is a mechanism provided by the Java Virtual Machine (JVM) garbage collector to reclaim the memory space occupied by objects without any object references from time to time in idle time.


    1) When the application is idle, that is, when no application thread is running, GC will be called. Because GC is performed in the thread with the lowest priority, the GC thread will not be called when the application is busy, except for the following conditions.

    2) GC will be called when the Java heap memory is insufficient. When the application thread is running and new objects are created during the running process, if the memory space is insufficient at this time, the JVM will forcibly call the GC thread in order to reclaim the memory for new allocation. If the memory allocation requirement is still not met after one GC, the JVM will perform another two GC attempts for further attempts. If the requirement is still not met, the JVM will report an "out of memory" error and the Java application will stop.

    3) As an optimization technique in the compilation process, the Java compiler can choose to assign a null value to the instance, thereby marking the instance as recyclable.

Since the main GC is determined by the JVM according to the system environment, and the system environment is constantly changing, the operation of the main GC is uncertain. It is impossible to predict when it will inevitably occur, but it can be determined for a long-running application. In other words, the main GC is repeated.

What is the reference point of GC Root:

1. Reference point object in java stack 

2. Objects referenced statically by methods 

3. Objects referenced by method constants 

4. Objects referenced by JNI in Native

5. Thread-living thread

         3) Out of memory OOM. The memory required by the application exceeds the memory allocated by the system for each application (that is, the memory leaks caused by the application are more, and the accumulated memory is not released, but it continues to apply). You can view the memory consumption changes through the menory-related tools of AS.

Example optimization points:

       Do not use the current activity context, use the application context,

        The animation should be released in time. Streams such as network files are closed in time.

        Cancel registration when the broadcast is launched. The service must be stopped after execution.

        Observer mode frameworks such as EventBus are manually unregistered.

        The collection class refers to the collection element object. Release list

        Leakage occurs when a singleton holds other contexts. The singleton life cycle is almost the same as the application.

        Static classes hold other references.

        Anonymous inner classes and non-static inner classes strongly hold external references. (If the internals are still held by external destruction, it will cause memory leaks. For example, a MyAscnyTask can be set to statically reference the Application context.) External variable methods can be accessed. If static internal classes If you don't pass parameters, you don't hold a reference. Autonomous life cycle. No access to the outside.

        Reduce the use of anonymous inner classes, and use weak references when using static inner classes.

LeakCanary detection principle:

1. RefWatcher.watch() creates a KeyedWeakReference to observe the object.

2. Then, in the background thread, it will check whether the reference has been cleared and whether the GC has not been triggered.

3. If the reference is still not cleared, it will save the stack information in the .hprof file in the file system.

4. HeapAnalyzerService is started in a separate process, and HeapAnalyzer uses the HAHA open source library to parse the stack snapshot file heap dump at the specified time.

5. From the heap dump, HeapAnalyzer found the KeyedWeakReference based on a unique reference key, and located the leaked reference.

6. In order to determine whether there is a leak, HeapAnalyzer calculates the shortest strong reference path to GC Roots, and then establishes a chain reference that leads to the leak.

7. This result is sent back to DisplayLeakService in the app process, and then a leak notification is displayed.

One sentence description:

After an Activity executes onDestroy(), put it into WeakReference, and then associate the Activity object of type WeakReference with ReferenceQueque. At this time, check whether there is the object from ReferenceQueque. If not, execute gc and check again. If there is no such object, it is judged that a memory leak has occurred. Finally, use HAHA, an open source library, to analyze the heap memory after dump.

Fourth, layout optimization

Need to optimize the situation:

       The UI thread, that is, the time-consuming operation in the main thread causes blocking.

       Too many Layout layers, over-drawing, rendering not completed within 16ms

       Too many animations are executed at the same time, and the CPU and GPU are overloaded

       View is over-drawn, only some elements need to be updated, but all elements are refreshed. Cause CPU/GPU load

       View frequently triggers onmeasure/onlayout/too much time-consuming and frequent rendering

       Frequent memory triggers too much GC, frequent memory creation, blocking rendering

       Redundant resources and logic cause slow loading and execution

       Open the display GPU view of the phone to view. The 4/3/2/1 layer display color is different. GPU rendering mode analysis. View rendering consumption

Proposal:

1. Use include and merge to reduce reuse and reduce levels.

2. The use of lightweight ViewStub does not occupy memory. Reduce the use of RelativeLayout. Surveying and mapping is time-consuming.

3. Use ConstraintLayout on complex pages.

4. Custom drawing View avoids time-consuming tasks in onDraw.

5. Speed ​​optimization (thread optimization and network optimization)

Thread optimization:

Avoid doing time-consuming operations on the main thread.

Asynctask: AsyncTask is Android's encapsulation of the thread pool Executor, multi-threaded, suitable for performing time-consuming operations, and updating the main thread after completion or during operation. Suitable for downloading apk files, etc.

HandlerThread : A lightweight asynchronous class that has been encapsulated by Android, which realizes the communication between the worker thread and the main thread (UI thread) , that is: the execution result of the worker thread is passed to the main thread, so that the relevant execution is executed in the main thread UI operation. Inherit Thread, single thread + asynchronous queue (Handler) scenarios , such as IO read and write operations on databases, files, etc. , application startup optimization, read data from the database to display the view, and use it in IntenService . Use: Create HandlerThread first, and call start, because start has a looper object. Among them are WorkHandler, which is used to work to send messages, and UIHandler is used to process main thread updates. To create WorkHandler, you need to receive the looper object of HandlerThread to process messages. If you need to update the UI, use UIHandler. 

Thread: suitable for a single time-consuming task.

Handler: to achieve communication between the child thread and the main thread. Looper/MessageQueue/Message

ThreadPool: Decompose tasks and distribute different threads for simultaneous processing. Manage and reasonably allocate threads, make effective use, adopt thread pool management, reuse internal threads,

IntentService : inherits service, suitable for performing time-consuming background tasks triggered by Ui. And the execution of these tasks can be fed back to the UI through a certain mechanism. Threaded tasks required  in the order , in the background.

Compared with service:

1. Service also runs in the main thread, so some time-consuming operations still need to be opened separately to execute the thread.

IntentService maintains a HandlerThread internally to perform business operations. After the execution is complete, stopSelf is automatically called, which is memory-friendly.

how to use:

Create a service to inherit intentService and implement business logic code in onHandleIntent.

Call startService(*) and register in the manifest.

Android 8.0 and above cannot be used, startService, startForegroundService can be used. Or use JobScheduler instead (above 5.0)

JobScheduler : Allows developers to create jobs that are executed in the background. When preset conditions are met, these jobs will be executed in the background. JobScheduler will collect a series of jobs and execute them together.

Network Optimization:

1. Request picture webP, thumbnails, etc.

2. Reasonable design of back-end interface, return data control, request refresh strategy

Six, power optimization

The above optimization to reduce CPU/GPU consumption is also to optimize power usage.

Can judge the network status and decide the requested action

Avoid invalid frequent network requests

Background tasks awaken the CPU as little as possible

Reasonable use of broadcasting and services

Seven, start optimization

Set the theme windowbackground on the startup page, set an interface instead of a white screen and a black screen. Give users the feeling of entering the app.

Avoid doing a lot of time-consuming operations and heavy initialization in the application.

Avoid I/O operations/deserialization/network operations/layout nesting.

Jetpack’s APP startUp. Implement the Initializer interface and provide a ContentProvider to run the initialization of all dependencies, avoiding each third-party library to use the ContentProvider to initialize separately, thereby improving the startup speed of the application.

8. Code/Package/Optimization

Avoid creating unnecessary objects, prefer static, optimize the use of static final, and avoid the use of floating-point numbers.

Code slimming. lint checks useless resouce and unused code,

The picture is compressed and can be drawn as much as possible.

Reuse resources, and the up and down arrows are realized through animation.

Different colors of the same image are realized through tint and tintMode below 5.0 with ColorFilter.

Use webP file format. AS provides conversion

Use vector graphics. nine-patch. svg

Code obfuscation uses Proguard tool. Compression optimization obfuscation

Componentization. Functional modules that do not involve business logic are managed on jcenter and downloaded on demand.

Plug-in: load the required apk

ndk supports cpu architecture instruction set type

Guess you like

Origin blog.csdn.net/guoyingmiss/article/details/110536101