Preface

It has been more than a year since my GoodWeather development. This App is completely open source, and I have published the development steps. I have encountered many problems during the development process. I just took this opportunity to talk about it. .

text

GoodWeather App is a weather app that can locate your current location in real time, check the local weather, and provide map positioning mode and voice input quick query method. The source code address of the project is as follows: GoodWeather, it is not convenient to download the source code. Download and install directly through the QR code to experience:

I used my spare time and rest to finish writing this project one after another. In the process of writing, I continued to improve and modify, and listened to readers’ suggestions to add corresponding functions. I also encountered some problems in the process, such as: ANR (program not responding), NullPointerException (null pointer exception), RunningTimeException (runtime exception), ArrayIndexOutOfBoundsException (array index out of bounds exception), IllegalArgumentException (illegal parameter), NumberFormatException (number format exception) and so on.

One, the problem

You will definitely encounter the above-mentioned abnormalities in your daily development, so let's talk about it in general.

① ANR

The ANR (full name: Application Not Responding) program is not responding. To solve the problem, you must first know the possibilities of the problem, and then check in combination with the actual situation of your current application, and finally find a solution. This is my idea, so what are the possibilities to cause ANR?

Possibility 1: The main thread is blocked, and there are too many time-consuming operations in the main thread (database reading and writing, file reading and writing, network requests, big data calculations, etc.). Possibility 2: Memory leaks. The startup page of the App is a high-definition picture, which can run normally on some mobile phones, and some mobile phones may crash. Possibility 3: Over-drawing. This statement is a combination of the above two possibilities. First, you draw the UI in the main thread, and secondly, if you draw a larger picture or draw it repeatedly, there is a possibility of ANR.

In practice, there are more possibilities than these three points. Let’s talk about how to solve it. The first possibility is that the main thread is blocked. Due to the execution of a large number of time-consuming operations, then the child thread must be used for time-consuming. The processing of the operation. For example, network requests, database reads and writes, and file reads and writes should all be executed in a sub-thread, and should not be processed in the main thread. For Activity, the UI thread is the main thread, and the UI thread is responsible for the drawing of the page UI. It will cause another problem, that is, when your view is drawn by the main thread, an error will be reported when you make changes in the child thread, so can the child thread refresh the view? Yes, but there is a premise, that is, your child thread creates the view, and the child thread is the UI thread of the view.

As for memory leaks, it is usually caused by improper resource handling. As a popular example, there are two bridges, A and B. A has a maximum load of 2 tons, and B has a maximum load of 6 tons. There are 100 vehicles to cross the bridge, and the load varies from 1 to 6 tons. The normal distribution is When the resource allocation is unreasonable, one-ton trucks will walk on a 6-ton bridge, and then a 6-ton truck will walk on a 2-ton bridge. Even if the quality of the bridge is better, it will eventually It may be that the example is not very appropriate, but the meaning should be very clear, that is, the resource is used reasonably, and it is recycled if it is not used. Returning to the problem I encountered before, it is high-definition pictures. There are many customizations for domestic mobile phones. Various manufacturers have changed Google's source code into a customized system, which is nothing for users, but it is very difficult for developers, because there is one problem you can't avoid, that is, adaptation.

The problem I encountered before was that I used a high-definition image on the startup page, and then it ran normally on my mobile phone, and then it crashed directly on a reader’s mobile phone. The error report is as follows:

What can be seen from this picture?
First of all, this is a runtime exception, and secondly, it has something to do with the drawing of the picture. Then such a combination is a problem of over drawing.
At that time, the reader found me, and then I started to investigate, first of all, what did I do when starting the App, there will be another point involved here, that is, the start-up optimization of the App, this point is very important. But the first thing to do is to solve the bug. After investigation, it is finally located as the problem of the picture. This shows that the customization of the mobile phone screen and its own system by domestic manufacturers is very different. The final solution is to modify the file for the high-definition picture to a large resolution. Under the folder, this is a relatively low-level error. I have placed regular folders before.

② NullPointerException

NullPointerException (Null Pointer Exception), I believe that friends who write Android in Java must have encountered a problem, that is, null, which is often referred to as an empty object. Generally speaking, a 90% probability of occurrence of this problem can be avoided by doing a good job during development. The biggest occurrence is when assigning values, as long as this appears, then the corresponding is that your program crashes, oh! The bonus this month is gone, and the bitterness of beating the workers has left tears of regret. So when using Java to develop Android, pay special attention to this point and pay attention to null. Kotlin does this very well because of the feature of air safety. So if there is a problem, the online project, the user will say that it will crash, not even saying when it crashed, what should you do? How to solve it? Through a third-party SDK, such as Youmeng, after you dock the SDK, after the release, when an error is reported, there will be error information and logs on the platform, so that the developer can quickly locate the problem, solve the problem, and then make an update to the App , This is perfectly resolved, although the deducted money cannot be returned, but you stop the loss in time. As for some other exceptions, they are all regular, and they can be resolved when they are discovered, during the development process. The most troublesome thing is how to locate and solve the problems after going online.

In fact, in actual App development, most of the problems can be found and resolved during the development and testing phases, but coincidentally, after going online, problems that have not been discovered before appear in the hands of users. At this time, development and testing It's about to shake each other's pot. It’s still necessary to find a solution after pulling, so for the current online project, it is necessary to connect a performance test and error collection SDK before going online. Below I will do this for my GoodWeather SDK docking and use.

Second, Umeng use

Click Umeng to enter the official website, then register and log in.

1. Create a platform application

After logging in, click to enter the workbench, where you can view the application information, if you have not created an application, add a new application.

Create an application on Youmeng and get AppKey

Register the app. At this point, the AppKey has been generated, and then select the product that needs to be activated. Here, select the application performance monitoring U-APM.

Confirm activation.

Copy this App Key to your own project, you will need it later. Open the build.gradle of the project and add the maven library. Two places, the same code:
groovy

maven { url 'https://repo1.maven.org/maven2/' }


Then open the build.gradle of the app module and add the following code in dependencies:
groovy
// Youmeng basic component library (all Youmeng business SDKs rely on the basic component library)

implementation "com.umeng.umsdk:common:9.4.2" //(必选)
implementation "com.umeng.umsdk:asms:1.4.1" // asms包依赖(必选)
implementation "com.umeng.umsdk:apm:1.4.2" // U-APM包依赖(必选)

Then Sync Now, synchronize the project.
Since the Umeng SDK needs to obtain the device information and network status of the mobile phone, the corresponding permissions need to be configured in AndroidManifest.xml
xml

<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permissionandroid:name="android.permission.READ_PHONE_STATE"/>
<uses-permissionandroid:name="android.permission.INTERNET"/>

Among them, READ_PHONE_STATE requires dynamic application.

Then it is initialized. One thing to note here is that you need to inform users to use the Umeng SDK in the "Privacy Policy". The reference terms are as follows: Use SDK name: Umeng SDK Service type: Please fill in according to the SDK function, such as application performance monitoring Platform U-APM collects personal information type: device information (IMEI/MAC/Android ID/IDFA/OpenUDID/GUID/SIM card IMSI geographic location information, etc.) Privacy policy link: https://www.umeng.com/page /policy The pop-up window of this privacy agreement should have an effect similar to this. Assuming this is your previous privacy policy,

Then you need to add instructions for using Umeng+SDK in this. Only after the user agrees can this initialization operation be carried out in the onCreate of the Application. There is a pre-initialization and a formal initialization. The pre-initialization is used when the program is first installed and run. Call the formal initialization after the user agrees to the privacy policy, such as the following figure

Okay, now that the docking is basically completed, let's use it below.

Two, use

① Log usage
After docking the Youmeng SDK, the relevant logs of Youmeng will be printed, and you don't need to print it again when it is online.

It can be turned off by the following line of code.
java
UMConfigure.setLogEnabled(boolean)

② Crash analysis
After completing the SDK docking, you can use the Java, Native crash analysis, and ANR analysis functions without additional access operations. If you need to collect Native, you can write it like this:
java

      //针对于Native崩溃信息采集
        final Bundle customInfo = new Bundle();
        customInfo.putBoolean("mCallNativeDefaultHandler",true);
        CrashApi.getInstance().updateCustomInfo(customInfo);

Crash callback (custom field)
java

//崩溃回调
        UMCrash.registerUMCrashCallback(new UMCrashCallback(){
            @Override
            public String onCallback(){
                return "App程序崩溃了";
            }
        });

Custom exception interface
In development, there is usually an exception try catch of its own, then the exception in the catch can also be transmitted to the background through the interface of the alliance, and then the developer can check it.
java

try {
            // 抛出异常的代码
        } catch (Exception e){
            UMCrash.generateCustomLog(e,"UmengException");
        }

use

③ Custom version number
Sometimes there may be multiple versions online, you can use the custom version number API to bind the data reported by the SDK to the App version information you specify.
java

UMCrash.setAppVersion("1.0.0", "release", "0001");

use

With these, you can wait for the error log of the program to be uploaded to Youmeng. First, find the place to view the log information on Youmeng. This place is really not easy to find

Click on stability.

use immediately.

Now you can check the related logs, so let's write a bug first.

For example, I wrote this code in the onCreate of the App's startup page.
java

 try {
            Thread.sleep(1000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

Then run, look at the AS console log

This log is very comprehensive, but this is the log printing of the Umeng SDK. Local debugging can be used. Is it transmitted to the platform? After all, the error message log of the online project is the key.

Obviously, I uploaded this error, and then swipe down to view the details of this error.


Click on the blue error report on the left

Here is the specific code line where the error was reported, and the information about the device you reported the error is here below, so that you can troubleshoot the cause, and then look down.

What is the reason for the error? The main thread sleeps for too long, causing the thread to block, the program is unresponsive, and ANR.
The behavior log on the right here is also very good, allowing you to know what you are doing on the current page.

This corresponds to page browsing, which is reasonable, because I really haven't done anything yet.

And this memory snapshot is to facilitate you to view the memory usage when the error is reported, and you can optimize it as appropriate.

The last custom field is obviously a crash callback written in the code.

This shows that the log of my custom field has also been uploaded.

Through introduction, access, usage, and log analysis, I understand the power of Youmeng, which is a boon for online projects. The submitted error information can be quickly uploaded, located, and quickly resolved.

More functions need to be explored by the developers themselves. This is just to play a role in attracting ideas. The mountains are high and the rivers are long, and there will be a period later~

Author: Li Longwei


性能优化实践者
11 声望220 粉丝