Chapter Eight Other Optimization of Performance Optimization (4)

Article Directory

Chapter Eight Other Optimization of Performance Optimization (4)

(1) Network optimization

(1) Necessity of network optimization

1. Small traffic consumption 2. Small
power consumption
3. Short user waiting time

(2) Tools for analyzing network connections

1、Network Monitor

It belongs to the built-in Monitor tool of Android, which tracks the data request of the selected application in real time. We can connect to the mobile phone, select and debug the application process, and then operate the page request that we need to analyze on the App.

2. Network proxy tool

In general, network proxy tools have two functions:

  • Intercept network request response packets, analyze network requests
  • Set up a proxy network, which is generally used to test different network environments in mobile app development, such as Wifi / 4G / 3G / weak network, etc.
    There are many proxy tools, such as Wireshark, Fiddler, Charles, etc.

(3) Optimization of network connection

1. Thinking

Reducing the radio active time
means reducing the frequency of network data acquisition. This reduces the radio's power consumption and controls power usage.
Reducing the size of the data packet obtained
can reduce traffic consumption and make each request faster, which is not good in the network situation. The case also has a good performance, improving the user experience.

2. Design

(1) Interface design
  • API design
    The API design between App and Server should consider the frequency of network requests, the status of resources, etc. so that the App can complete the display of business requirements and interfaces with fewer requests.
  • Gzip compression
    Use Gzip to compress request and response, reduce the amount of data transmitted, and thus reduce traffic consumption.
  • The use of Protocol Buffer instead of JSON
    Protocol Buffer is a data exchange format introduced by Google. If our interface transmits a large amount of data each time, we can consider protobuf, which will be much smaller than JSON data.
    JSON also has its advantages, but Higher readability. Reduce the amount of data (of course, the convenience of mapping to POJO)
  • The size of the
    picture is much larger than that of the interface request. Therefore, it is also a point that we need to optimize. We can inform the server of the width and height of the picture when obtaining the picture, so that the server can give a suitable picture. Prevent wastage.
(2) Network cache

Proper caching can not only make our application look faster, but also avoid some unnecessary traffic consumption.

  • When there is a network, according to the set Cache Control time, it is determined whether to use the cache or make a network request again.
  • Use the cache directly without a network environment to ensure a reading experience.
(3) Packaging network request

When the interface design cannot meet our business needs. For example, an interface may need to request multiple interfaces, or the network is good, and we want to get more data when in the Wifi state.
At this time, we can package some network requests, for example At the same time as requesting the list, the detailed data of the item item with a high Header click rate is obtained.

(4) Monitor relevant status

By monitoring the status of the device: sleep status, charging status, network status
combined with JobScheduler to make network requests according to the actual situation. For example, Splash splash screen advertising images, we can download and cache to the local when connected to Wifi; News App can be in Charging, offline cache in Wifi state.

(5) Weak network testing & optimization

In addition to normal network optimization, we also need to consider the performance of the app in the case of a weak network. Creating and starting an Android emulator can set the network speed and delay
weak network optimization, which essentially allows users to fluently in the case of a weak network. Use our App. All we have to do is to combine the above optimization items:

  • Compression / reduction of data transmission
  • Using cache to reduce network transmission
  • For weak networks (mobile networks), pictures are not loaded automatically
  • Interface first feedback, request delayed submission
(6) Server optimization

Including server-side code development, deployment methods, etc.

(4) The impact of Http and Https on access speed (performance)

HTTPS plays a very critical role in protecting user privacy and preventing traffic hijacking, but at the same time, HTTPS will also reduce user access speed and increase the computing resource consumption of the website server.
The impact mainly comes from two aspects:
a. Network RTT (round trip time) increased by protocol interaction.
b. The calculations related to encryption and decryption take time.

1. Increased network time

The network of the first HTTP request is time-consuming. Users only need to complete the TCP three-way handshake to establish a TCP connection and can directly send HTTP requests to obtain application layer data. In addition, there is no need to consume computing resources during the entire access process. The HTTPS access process is much more complicated than HTTP. In some scenarios, using HTTPS access may increase 7 RTTs.

2. The calculation time increases

The encryption and decryption process during key exchange requires very time-consuming calculation of CPU resources

(2) Optimization of battery usage

(1) Tool for analyzing electricity usage

a.Batterystats & bugreport
b.Battery Historian

(2) Main power consumption factors

1. Network request

2、WakeLock

In order to optimize the use of power, the Android system itself will go to sleep when there is no operation to save power.
You can use WakeLock to keep the CPU running, or prevent the screen from dimming / turning off, so that the phone can still do when the user is not operating Some things (such as playing a video screen); or perform other operations after turning off the screen.

3、GPS

(3) Power optimization

1. Optimize network requests

(See network optimization)

2. Use WakeLock with caution

(1) WakeLock acquisition and release appear in pairs
(2) Use timeout WakeLock to prevent abnormal release without release

// Acquires the wake lock with a timeout.
acquire(long timeout)

3. Monitor phone charging status

BatteryManager will send a continuous broadcast containing the charging status.We can get the charging status and battery details through this broadcast:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

Note: Because this is a continuous broadcast, we don't need to write a receiver, we can get the relevant data directly through the intent.

(1) Get the charging status and power details through Intent
For example, if the device is charging:

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BATTERY_PLUGGED_AC;

(2) Register the receiver to monitor the charging status changes.
As long as the device is connected or disconnected from the power supply, the BatteryManager will broadcast the corresponding operation. We can register the receiver to monitor:

<receiver android:name=".PowerConnectionReceiver">
  <intent-filter>
    <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
    <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
  </intent-filter>
</receiver>

Monitoring the battery status allows us to put some operations on charging or enough power to improve the user experience. For example, user data synchronization, log upload, etc.

4、Doze and App Standby

Android 6.0 provides two technologies, Doze and App Standby, to save power.
(1) Doze is
dozing. If the device is idle for a long period of time, Doze technology will reduce power consumption by delaying background network activities and CPU operation.
( 2) App Standy
App Standby. Not the App that has recently been "favored" by users, App Standy will delay the background network activities of this app.

5. About positioning

(1) Use GPS for positioning, please remember to close in time

// Remove the listener you previously added
locationManager.removeUpdates(locationListener);

(2) Reduce the update frequency
(3) Choose GPS or network or both according to the actual situation. Using only one will reduce the power consumption.

(3) Detailed explanation of ANR

(1) Introduction to ANR

1. Definition

The full name of ANR is Application Not Responding, which is "application not responding".

2. Causes

In Android, the App ’s responsiveness is monitored by the Activity Manager and Window Manager system services. Generally, the ANR dialog box will pop up in the following two situations:
(1) Cannot respond to user input events (such as keyboard input, touch) within 5s (Screen, etc.).
(2) BroadcastReceiver cannot end within 10s.
The primary reason for the above two situations is that the main thread (UI thread) has done too many blocking and time-consuming operations, such as file read and write, database read and write, Internet queries, etc.

3. How to avoid

Don't do heavy operations in the main thread (UI thread).

(2) ANR analysis

1. Obtain the trace file generated by ANR

When ANR is generated, the system will generate a traces.txt file under / data / anr /. You can export it to the local through the adb command:

$adb pull data/anr/traces.txt .

2. Analyze trace.txt

1. ANR caused by ordinary blocking
 - locked <0x35fc9e33> (a java.lang.Object)
  at java.lang.Thread.sleep(Thread.java:985) // 主线程中sleep过长时间, 阻塞导致无响应.
2. CPU full load
100%TOTAL: 5.9% user + 4.1% kernel + 89% iowait

The CPU occupies 100% and is fully loaded. I think most of it is occupied by IOwait, that is, IO operations. At this time, analyzing the method call stack, you will generally find that there are frequent file reads and writes or database read and write operations in the method on the main thread.

3. Memory problem (memory leak / overflow)
size: 17036 23111 N/A 40147
allocated: 16484 20675 N/A 37159
free: 296 2436 N/A 2732//free内存所剩无几

3. ANR processing

1. The main thread is blocked

Open up separate child threads to handle time-consuming blocking transactions.

2. CPU full load / IO blocking

I / O blocking generally means that file reading and writing or database operations are executed on the main thread, or it can be executed asynchronously by opening up sub-threads.

3. Insufficient memory

Increase VM memory, use the largeHeap attribute, troubleshoot memory leaks (memory optimization), etc.

(3) Avoid ANR method

Focusing on prevention, there is the concept of main thread and sub-thread, recognize the blocking point of the code, and make good use of threads.
Idea: Don't do heavy operations in the main thread (UI thread).

1. Operations performed on the main thread

  • All life cycle callbacks of Activity are executed on the main thread.
  • Service is executed on the main thread by default.
  • BroadcastReceiver's onReceive callback is executed on the main thread.
  • The handleMessage, post (Runnable) of the Handler of the looper that does not use the child thread is executed on the main thread.
  • In addition to doInBackground, the callback of AsyncTask is executed on the main thread.
  • View's post (Runnable) is executed on the main thread.

2. The way to use sub-threads

1.Thread mode

Inherit Thread

class PrimeThread extends Thread {
    long minPrime;
    PrimeThread(long minPrime) {
        this.minPrime = minPrime;
    }

    public void run() {
        // compute primes larger than minPrime
         . . .
    }
}

PrimeThread p = new PrimeThread(143);
p.start();

Implement the Runnable interface

class PrimeRun implements Runnable {
    long minPrime;
    PrimeRun(long minPrime) {
        this.minPrime = minPrime;
    }

    public void run() {
        // compute primes larger than minPrime
         . . .
    }
}

PrimeRun p = new PrimeRun(143);
new Thread(p).start();
2.AsyncTask method

AsyncTask starts asynchronous tasks

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
    // Do the long-running work in here
    // 执行在子线程
    protected Long doInBackground(URL... urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int) ((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }

    // This is called each time you call publishProgress()
    // 执行在主线程
    protected void onProgressUpdate(Integer... progress) {
        setProgressPercent(progress[0]);
    }

    // This is called when doInBackground() is finished
    // 执行在主线程
    protected void onPostExecute(Long result) {
        showNotification("Downloaded " + result + " bytes");
    }
}

// 启动方式
new DownloadFilesTask().execute(url1, url2, url3);
3.HandlerThread

A way of combining Handler and Thread in Android. By default, the Handler's handleMessage is executed on the main thread, but if I pass a looper of a child thread to this Handler, handleMessage will be executed in this child thread. HandlerThread It is such a combination:

// 启动一个名为new_thread的子线程
HandlerThread thread = new HandlerThread("new_thread");
thread.start();

// 取new_thread赋值给ServiceHandler
private ServiceHandler mServiceHandler;
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
      super(looper);
    }
    
    @Override
    public void handleMessage(Message msg) {
      // 此时handleMessage是运行在new_thread这个子线程中了.
    }
}
4.IntentService

Service runs on the main thread, but IntentService runs on the child thread.
In fact, IntentService implements a HandlerThread + ServiceHandler mode.

5.Loader method

The data loader introduced in Android 3.0 can be used in Activity / Fragment. It supports asynchronous loading of data, and can monitor the data source to deliver new results when the data changes. The commonly used CursorLoader is used to load database data.

// 使用LoaderManager来初始化Loader
getLoaderManager().initLoader(0, null, this);

//如果 ID 指定的加载器已存在,则将重复使用上次创建的加载器。
//如果 ID 指定的加载器不存在,则 initLoader() 将触发 LoaderManager.LoaderCallbacks 方法 //onCreateLoader()。在此方法中,您可以实现代码以实例化并返回新加载器

// 创建一个Loader
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // This is called when a new Loader needs to be created.  This
    // sample only has one Loader, so we don't care about the ID.
    // First, pick the base URI to use depending on whether we are
    // currently filtering.
    Uri baseUri;
    if (mCurFilter != null) {
        baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
                  Uri.encode(mCurFilter));
    } else {
        baseUri = Contacts.CONTENT_URI;
    }

    // Now create and return a CursorLoader that will take care of
    // creating a Cursor for the data being displayed.
    String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
            + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
            + Contacts.DISPLAY_NAME + " != '' ))";
    return new CursorLoader(getActivity(), baseUri,
            CONTACTS_SUMMARY_PROJECTION, select, null,
            Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}

// 加载完成
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Swap the new cursor in.  (The framework will take care of closing the
    // old cursor once we return.)
    mAdapter.swapCursor(data);
}

(4) Performance analysis tools

Insert picture description here

1. Official tools

Android itself provides us with a lot of App performance testing and analysis tools, and most of them are integrated into Android Studio or DDMS, which is very convenient to use.
1.1 StrictMode
(1) shows that as the
name implies, "strict mode" is mainly used to restrict the application to do some Things that do not meet performance specifications. Generally used to detect time-consuming operations and blocking in the main thread. After enabling StrictMode, if you do some operations such as reading and writing files, network access, etc. in the thread, some warnings will be output in the Log console, warning The information includes Stack Trace to show where something went wrong.
(2) Function
Mainly used for main thread optimization analysis
1.2 Systrace
(1) Explain that
Systrace is a tool to collect and detect time information, it can show where CPU and time are consumed Now, every process and thread has done something in its CPU time slice. And it will indicate what went wrong, and give Fix suggestions.
It is recorded in a trace file (html). You can use Chrome directly Open the browser to view. The interface is as follows:
Insert picture description here
(2) Function
Used to analyze the drawing time of the UI, combined with Hierarchy Viewer to improve the UI Performance. It can also be used to discover time-consuming operations.
1.3 Hierarchy Viewer
(1) shows that
Hierarchy Viewer provides a visual interface to observe the layout level, allowing us to optimize the layout level, delete unnecessary and unnecessary View levels, and improve the layout Speed. It
Insert picture description here
is necessary to explain:
The three points marked by the red box in the above figure are the key analysis data. From the left, they represent the performance of View's Measure, Layout and Draw. In addition, the color indicates the time index of the View, divided into:

  • Green, indicating that the performance of this View is faster than more than 50% of the View in the View Tree.
  • Yellow, indicating that the performance of this View is slower than that of more than 50% of the View Tree.
  • Red, indicating that the performance of the View is the slowest in the View Tree.
    (2) Function
    Used for View level analysis, you can analyze the performance blocking points in the View Tree, so as to
    treat the symptoms, improve the layout performance. 1.4 TraceView
    (1 ) Description
    Insert picture description here
    A graphical tool used to display and analyze the execution time of a method.
    (2) Function
    Analysis method call stack and its execution time, optimized method execution.
    1.5 Memory Monitor
    (1) Description
    memory usage detector, which can detect in real time The current Application memory usage and release information, and displayed in a graphical interface.
    (2) The role is
    Insert picture description here
    used for memory analysis, memory leak troubleshooting is the best choice. Can be combined with heap viewer, allocation tracker to analyze. Can export hprof file Combined with a third-party MAT tool to analyze the leak point.
    1.6 Other Monitor
    (1) shows that the
    Android Studio Monitor also provides three other Motinor — CPU, GPU, Network.
    (2) The function is
    used to track and monitor the CPU, GPU and Network respectively The use of extreme changes can be used as a guide for network optimization, traffic optimization and rendering optimization.
    1.7 Other
    Android development There are also many options for monitoring performance in the user mode, which can be used:
    Insert picture description here
    Developer options

2. Third-party tools

2.1 Google ’s Battery Historian
(1) Description
of the tool produced by Google that uses the bugreport file of the Android system to do power usage analysis.
(2) Function
Used for power usage analysis.
2.2 Emmagee (NetEase)
(1) Description
for Android App Comprehensive test and analysis of CPU, memory, network, power, etc.
(2) Function It
is more suitable than the official tool for Chinese people to do the overall performance analysis of the App.
2.3 leakcanary
(1) shows that
Square is produced, it must be a boutique. Similar to App The memory leak monitoring tool of the probe.
(2) Function It is
integrated into the App, which is the best way to prevent memory problems.

Published 74 original articles · won 15 · views 6255

Guess you like

Origin blog.csdn.net/qq_29966203/article/details/90473690