"One Enough Series" Android App Optimization Knowledge Points Collection

My new book "Android App Development Introduction and Actual Combat" was published by People's Posts and Telecommunications Publishing House in August 2020. Welcome to buy.

Books For details, see: https://blog.csdn.net/ddnosh/article/details/107666187

books to buy Address: Jingdong Dangdang Lynx

Picture name


Welcome to join the Android development and communication QQ group:
Android development technology exchange

1. [Layout optimization]

principle

60fps
cpu and gpu work coordination: CPU handles logical operations, GPU handles floating-point operations;

Detection method

System Settings-Developer Options-Debug GPU overdrawing.
Colorless: no overdrawing, each pixel is drawn once.
Blue: each pixel is drawn once more. Large areas of blue are acceptable. If the entire window is blue, you can try to optimize and reduce one draw.
Green: Each pixel is drawn twice more.
Light red: each pixel is drawn 3 more times. Generally speaking, it is acceptable that this area does not exceed 1/4 of the screen.
Crimson: Each pixel is drawn 4 times or more. Severely affect performance and need to be optimized to avoid dark red areas.

Optimization

Reduce GPU overdraw

If not necessary, it is not recommended to set the activity background;

Reduce CPU work

Layout optimization

  1. include、merge、ViewStub
  2. ConstraintLayout lower level
  3. The choice of RelativeLayout and LinearLayout:
    RelativeLayout has fewer levels, but child View will call onMeasure twice; LinearLayout has more levels, which will increase memory, and if the weight attribute is used, onMeasure will be called twice. Without affecting the depth of the hierarchy, use LinearLayout and FrameLayout instead of RelativeLayout.
  4. SurfaceView 或 TextureView

tool

  1. uiautomator.bat
    analyzes the xml layout;
  2. monitor.bat
    green: Indicates that the performance of this View is faster than 50% of the View in the View Tree; for example, the green dot representing Measure means that the measurement time of this view is faster than that of the view object in the tree 50%.
    Yellow: Indicates that the performance of the View is slower than that of more than 50% of the Views in the View Tree;
    Red: Indicates that the performance of the View is the slowest in the View Tree;

2. [Memory Management]

Memory model

JVM: method area, virtual machine stack, local method stack, heap, program counter

Memory jitter

The memory allocation speed is greater than the recovery speed.
For example, splicing string strings and replacing them with stringbuffer or stringbuilder.

Recovery algorithm

Mark removal algorithm Mark-Sweep
copy algorithm Copying
mark compression algorithm Mark-Compact
generational collection algorithm

tool

  1. profiler
  2. MemoryAnalyzer
  3. leakcanary

Ways to solve memory leaks

  1. Singleton
  2. handler
  3. Static variable
  4. Anonymous inner class
  5. Register and unregister
  6. Timed task
  7. Resource shutdown
  8. Property animation
  9. Webview memory leak (open a new process)
  10. Other notes:
    replace static with static final for basic data types;

Comparison between for loop and iterator:
ArrayList is faster for random access, while the get() method in the for loop uses random access, so in ArrayList, the for loop is faster

    采用LinkedList则是顺序访问比较快,iterator中的next()方法,采用的即是顺序访问的方法,因此在LinkedList里,使用iterator较快

From a data structure perspective, for loops are suitable for accessing sequential structures and can quickly obtain specified elements based on subscripts. And Iterator is suitable for accessing chain structures, because iterators are positioned through next() and Pre(). There is no order to access Collection.

    而使用 Iterator 的好处在于可以使用相同方式去遍历集合中元素,而不用考虑集合类的内部实现(只要它实现了 java.lang.Iterable 接口),如果使用 Iterator 来遍历集合中元素,一旦不再使用 List 转而使用 Set 来组织数据,那遍历元素的代码不用做任何修改,如果使用 for 来遍历,那所有遍历此集合的算法都得做相应调整,因为List有序,Set无序,结构不同,他们的访问算法也不一样.(还是说明了一点遍历和集合本身分离了)

3. [Network Optimization]

solution

  1. API interface design: data obtained from multiple apis are combined into one api;
  2. GZip compresses request and response;
  3. Protocol Buffer代替json;
  4. Get the URL of the picture to inform the server of the width and height of the picture required; for
    example, return pictures of different sizes according to different network conditions; use webp;
  5. Resuming the downloading of large files;
  6. Incremental packages: bsdiff and bspatch;
  7. The data
    requested by the network is cached; for example, the data obtained by the network request is put into the database, and the page is first obtained from the database every time the page is loaded, and the UI and the database are updated after the network data is obtained;
  8. JobScheduler performs download tasks under wifi, such as advertisements;
    JobScheduler is used after 5.0, and WorkManager is used after 8.0.
  9. Webview loading, related to front-end html page optimization;

Special project: Weak network optimization

Cache the request first, and then send the request through JobScheduler when the network condition is good. Like like.
Configure the cache through OkHttpClient, when the phone is not connected to the Internet, you can load data directly from the cache. You can also set read, write, and connection timeouts.

4. [Apply weight reduction]

  1. AndResGuard resource file slimming;
  2. Lint removes useless resources: Analyze> Run Inspection By Name> unused resources;
  3. proguard: enable minifyEnabled obfuscation code, you can compress files, and use shrinkResources to remove useless resources;
  4. Picture:
    use svg format (xml format);
    tinypng compression;
    webp format;
  5. Plug-in
  6. Only keep one so file of cpu architecture: armeabi-v7a
  7. Remove multiple languages;
  8. Remove third-party libraries, such as rxjava, etc.;

5. [Start optimization]

1. Start black and white screen

1. Method 1: Customize the background image + full screen The
black and white screen is because when the system is creating the process, the
first solution we think of is to replace the black and white color with a picture, and it can be set to full screen display for better effect.
First define a BaseTheme:
··· xml

<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

···
Then define the style of a startup page, inherited from BaseTheme.

<style name="SplashTheme" parent="AppTheme">
        <item name="android:windowFullscreen">true</item> // 全屏
        <item name="android:windowBackground">@mipmap/splash</item> //图片
</style>

The disadvantage of this solution is that there will be a jitter process from full screen to non-full screen page (such as MainActivity).
2. Method 2: Transparent + disable window preview animation

<style name="SplashTheme" parent="AppTheme">
        <item name="android:windowDisablePreview">true</item>  //禁用窗口预览动画
 		<item name="android:windowBackground">@null</item> //不设置背景
</style>

This solution is suitable for scenarios where the startup page does not need to be time-consuming. If it takes a period of time to start, the user will think that there will be no response after clicking the desktop icon, and the experience is not good.
3. Method 3 (recommended): Customize the background image + transparent status bar.
Combining the shortcomings of Method 1 and Method 2, we propose a solution that is to use a custom background image + transparent system status bar.

    <style name="SplashTheme" parent="AppTheme">
        <item name="android:windowTranslucentStatus">false</item> //<!-- 将状态栏透明化,设置为true,状态栏有阴影,false则无阴影 -->
        <item name="android:statusBarColor">@android:color/transparent</item> //设置状态栏颜色为透明色
        <item name="android:windowBackground">@mipmap/splash</item>
    </style>

This kind of scheme will neither produce the shaking problem, nor the unresponsive scene that appears after clicking the desktop icon.

2. Start time-consuming test

Start is divided into cold start and hot start.
A cold start means that the process is killed or started for the first time; a
warm start means that the Activity is recycled, but the Application still exists and does not need to be recreated, and the corresponding process is still there.
1. Command line
Command line: adb shell am start -S -R 3 -W com.androidwind.androidquick.sample/.SplashActivity
-S means forcibly stop before each start, -R means the number of repeated tests.
The results are as follows:

Stopping: com.androidwind.androidquick.sample
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.androidwind.androidquick.sample/.SplashActivity }
Status: ok
Activity: com.androidwind.androidquick.sample/.SplashActivity
ThisTime: 2851
TotalTime: 2851
WaitTime: 2894
Complete

Disadvantages:
1. A certain activity may need to be reached after multiple activity jumps, and need to superimpose the start time of these activities;
2. The statistical time is inaccurate, for example, only the start and initialization time of the activity is calculated, and the waiting time is not calculated ;
3. The statistical activity needs to be set or android:exported="true";

2. Write a timing tool TimeUtils which
mainly distinguishes the time-consuming algorithm of hot start and cold start.
Cold start = application start time + hot start time;
hot start refers to the start time of Activity.
3. The third-party tool nimbledroid
https://nimbledroid.com/

3. Optimization plan

The App loading process is more complicated, and the optimization points that can be controlled in our client development are Application and Activity.

Lazy loading

  1. Application: The SDK
    tries to delay the initialization of the third-party SDK, and then load it when it is used.
  2. Application: static variables For
    example, for some static objects, if the initialization time is long and they are not used at startup, you can consider to initialize them when they are used for the first time.
  3. Activity: Viewstub
    ViewStub will be loaded when it is used.
    In short, the purpose is to reduce the View hierarchy and reduce the View drawing time.
    For example, use ConstraintLayout.
  4. Activity:Fragment
    lazyfragment

Open child thread processing

Thread, ThreadPool, AsyncTask, IntentService, HandlerThread, RxJava, etc.
Note that the child thread cannot block the main thread. For example, if shared preferences loads a large-capacity SD card file, the main thread will be blocked. The join of Thread and the get of FutureTask also block the main thread.

6. [Power Optimization]

tool

Battery-Historian

Power consumption positioning

CPU processing
positioning
network
image

optimization

The optimization methods are mainly reflected in the following aspects:

  1. Reduce the power consumption of CPU and GPU as much as possible. Try to use timers sparingly. Optimize I/O operations. ART replaces Dalvik, reduces CPU work, reduces space, and saves power

Don't write small data frequently, but accumulate to a certain amount and then write.
Dispatch_io can be used to read and write a large amount of data. GCD has been optimized internally.
When the amount of data is relatively large, it is recommended to use a database

  1. Network optimization
    Reduce network data compression (XML -> JSON -> ProtoBuf). ProtoBuf is recommended if possible.
    If the requested return data is the same, you can use NSCache for caching.
    Use breakpoints to resume transmission to avoid re-downloading after network failure.
    When the network is unavailable, do not try to make a network request. For a
    long-time network request, provide an operation
    that can be canceled. Use batch transmission. When downloading a video stream, try to download in large chunks. You can download multiple ads at once

Positioning optimization

If you just need to quickly determine the user's location, it is best to use the requestLocation method of CLLocationManager. After positioning is completed, it will automatically let off positioning hardware
if not a navigation application, try not updated in real time position, positioning complete turn off location services
to minimize positioning accuracy, for example, try not to use the highest accuracy kCLLocationAccuracyBest
needed background positioning, try to set pausesLocationUpdatesAutomatically If it is YES, the system will automatically suspend location updates when the user is unlikely to move.
Try not to use startMonitoringSignificantLocationChanges, and give priority to startMonitoringForRegion:

Hardware detection optimization

When the user moves, shakes, or tilts the device, motion events are generated, and these events are detected by hardware such as accelerometers, gyroscopes, and magnetometers. When testing is not required, these hardware should be shut down in time

other

Get power report and analysis;
try not to use
wakelock ; JobScheduler replaces Service, and runs these tasks when connected to wifi or charging.

7. [Image optimization]

  1. ARGB_8888 system default, inSampleSize sampling rate;
  2. Put the pictures in a high-density directory as much as possible, so that the method multiple is below 1;
  3. PNG has an A channel and can be compressed with tinypng and other tools before use;
  4. Use webp;
  5. Use .9 pictures;
  6. Use picture frames, such as Glide;

8. [Code Optimization]

  1. Refactoring;
  2. Architecture optimization: componentization, plug-inization;

Welcome to pay attention to my technical public number: national programmers , our goal: output dry goods

  1. Share original technical articles every day
  2. Massive free technical materials and video learning resources
  3. Share the ways to make money and lead programmers to financial freedom
Picture name

Guess you like

Origin blog.csdn.net/ddnosh/article/details/108468843