Overview

App Performance Management (APM) of AppGallery Connect provides minute-level app performance monitoring capabilities. By integrating the APM SDK, you can quickly integrate APM without coding. APM allows you to view and analyze app performance data collected in AppGallery Connect to comprehensively understand the performance features of your app, and quickly and accurately rectify performance problems to continuously improve user experience.

What You Will Create

In this codelab, you will build an app that integrates APM. In addition, you can manually trigger network requests to test whether APM can monitor network performance and learn how to view and analyze app performance problems.

What You Will Learn

Development Environment and Skill Requirements

Device Requirements

To integrate APM of AppGallery Connect, you must complete the following preparations:

For details, please refer to Preparations for Integration in AppGallery Connect.

Integrating the APM Plug-in

  1. Open the project-level build.gradle file and add the following code to add the APM plug-in dependency:
    buildscript { repositories { // Add the maven repository maven { url 'http://developer.huawei.com/repo/' } } dependencies { // To benefit from the latest APM feaures, update your Android Gradle Plugin // dependency to at least v3.5.3 classpath 'com.android.tools.build:gradle:3.5.3' // Add agc plugin dependence classpath 'com.huawei.agconnect:agcp:1.4.1.300' // Add the dependency for the APM plugin classpath 'com.huawei.agconnect:agconnect-apms-plugin:1.5.1.301' } }
  2. Open the app-level build.gradle file and add the following code to integrate the APM plug-in:
  3. apply plugin: 'com.android.application' // Apply the AppGallery Connect plug-in. apply plugin: 'com.huawei.agconnect' // Apply the APM plug-in. apply plugin: 'com.huawei.agconnect.apms' dependencies { //.. }

Integrating the APM SDK

If you are using Android Studio, you need to integrate the APM SDK into your Android Studio project before development.

  1. Sign in to AppGallery Connect, click My projects, and click the project for which you need to integrate the APM SDK.
  2. Go to Project Setting > General information, and click agconnect-services.json to download the configuration file.
  3. Copy the agconnect-services.json file to the app's root directory of your Android Studio project.
  4. Open the app-level build.gradle file and add the following code to integrate the APM SDK:
  5. dependencies { // Add APM SDK library dependency implementation 'com.huawei.agconnect:agconnect-apms:1.5.1.301' }
  6. Add the following items to app-level obfuscation configurations:
  7. -keep class com.huawei.agconnect.apms.**{*;} -dontwarn com.huawei.agconnect.apms.** -keep class com.hianalytics.android.**{*;} -keep class com.huawei.updatesdk.**{*;} -keep class com.huawei.hms.**{*;} -keep interface com.huawei.hms.analytics.type.HAEventType{*;} -keep interface com.huawei.hms.analytics.type.HAParamType{*;} -keepattributes Exceptions, Signature, InnerClasses, LineNumberTable
  8. Click Sync Now to synchronize the configuration.
  9. Build the app.

You can create a page in your Android Studio project and design the UI according to the following figure, with six buttons required: One button is used to trigger network monitoring events and the other two are used to enable and disable APM performance data reporting.

You can manually trigger a network request and check whether the network performance indicators are normal on the performance management page of APM. The app launch and screen rendering events are automatically reported when an app is launched.

  1. Add three buttons, namely Send Network Request, APMS Collection ON, and APMS Collection OFF, to the activity layout file of your app.
  2. Create the HttpUtil.java file, add the following code, and define the request sending method:
    static private String URL = "https://developer.huawei.com/consumer/cn/"; static private MediaType MEDIATYPE = MediaType.parse("text/x-markdown; charset=utf-8"); static private String REQUESTBODY = "apms http request test"; static public void oneRequest() { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(URL) .post(RequestBody.create(MEDIATYPE, REQUESTBODY)) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d("apmsAndroidDemo", "onFailure: " + e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d("apmsAndroidDemo", "onResponse: Success"); } }); }
  3. Tap Send Network Request to call the execute method of Okhttp3 to report a network event.
    Button sendNetworkRequestBtn = findViewById(R.id.btn_network); sendNetworkRequestBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("apmsAndroidDemo", "send network request."); HttpUtil.oneRequest(); } });

In this codelab, you can manually trigger the reporting of custom indicators and check whether the indicators can be displayed properly on the app performance management page.
Add three buttons, namely Send Custom Event, Send Custom Event By annotation, and Send Custom Network Event, to the activity layout file of your app, to report custom events by calling an API, report custom events through annotation, and report custom network events by calling an API, respectively.

Reporting Custom Events by Calling an API

  1. Set the button tap event for the Send Custom Event button in MainActivity.java.
  2. findViewById(R.id.custom_normal_event).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("apmsAndroidDemo", "send a custom event"); sendCustomEvent(); } });
  3. Add the following code to the MainActivity.java file to define a custom event, and add the Processing result and Status properties and measurement Processing times to the event. When the button is tapped, the properties can be reported to the cloud.
  4. // Define a custom event. public void sendCustomEvent() { CustomTrace customTrace = APMS.getInstance().createCustomTrace ("CustomEvent1") customTrace.start(); businessLogicStart(customTrace); businessLogicEnd(customTrace); customTrace.stop(); } public void businessLogicStart(CustomTrace customTrace) { customTrace.putMeasure("ProcessingTimes", 0); for (int i = 0; i < 5; i++) { customTrace.incrementMeasure("ProcessingTimes",1); } } public void businessLogicEnd(CustomTrace customTrace) { customTrace.putProperty("ProcessingResult","Success"); customTrace.putProperty("Status","Normal"); }

Reporting Custom Events by Annotation

  1. Set the button tap event for the Send Custom Event By annotation button in MainActivity.java
    findViewById(R.id.custom_normal_event_by_annotation).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("apmsAndroidDemo", "send a custom event by annotation"); sendCustomEventByAnnotation(); } });
  2. Add the following code to MainActivity.java to define a custom event. When the button is tapped, the event can be reported to the cloud.
    private void sendCustomEventByAnnotation() { customEventHandle(); } // define custom event by annotation @AddCustomTrace (name = "CustomEvent2") public void customEventHandle() { }

Reporting Custom Network Events by Calling an API

  1. Set the button tap event for the Send Custom Network Event button in MainActivity.java.
    findViewById(R.id.custom_network_event).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("apmsAndroidDemo", "send a custom network event"); new Thread(new Runnable() { @Override public void run() { HttpUtil.customNetworkEvent(); } }).start(); } });
  2. Add the following code to HttpUtil.java to define a custom event, call an API to set the URL and number of bytes to be sent before the network connection starts, set the response code, response size, and response type after a network response, and set the property that specifies the actual transmitted size and property that contains exception information. All these properties can be reported to the cloud when the Send Custom Network Event button is tapped.
    static private String URL = "https://developer.huawei.com/consumer/cn/"; static private MediaType MEDIATYPE = MediaType.parse("text/x-markdown; charset=utf-8"); static private String REQUESTBODY = "apms http request test"; static public void customNetworkEvent() { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(URL) .post(RequestBody.create(MEDIATYPE, REQUESTBODY)) .build(); // define custom network event NetworkMeasure networkMeasure = APMS.getInstance().createNetworkMeasure(URL, "POST"); networkMeasure.setBytesSent(request.headers().byteCount()); long bytesRecive = 0L; networkMeasure.start(); try { Response response = okHttpClient.newCall(request).execute(); networkMeasure.setStatusCode(response.code()); if (response.body() != null) { networkMeasure.setBytesReceived(response.body().contentLength()); networkMeasure.setContentType(Objects.requireNonNull(response.body().contentType()).toString()); bytesRecive = dealResponseBody(response.body()); response.body().close(); } networkMeasure.putProperty("TrasnmittedBytes", String.valueOf(bytesRecive)); networkMeasure.stop(); } catch (IOException e) { networkMeasure.setStatusCode(0); classErrorMessage(networkMeasure, e); networkMeasure.putProperty("ErrorInformation", e.getMessage()); networkMeasure.putProperty("TrasnmittedBytes", String.valueOf(bytesRecive)); networkMeasure.stop(); } } private static void classErrorMessage(NetworkMeasure networkMeasure, Exception e) { if (e instanceof UnknownHostException) { networkMeasure.putProperty("ErrorInformation", "DNS resolution failed."); } } private static long dealResponseBody(ResponseBody body) throws IOException { InputStream inputStream = body.byteStream(); byte[] result = new byte[1000]; long len = 0; long readBytes = 0; while ((len = inputStream.read(result)) != -1) { readBytes += len; } return readBytes; }

In this codelab, you can manually trigger the reporting of an ANR error and check whether the ANR data can be displayed properly on the app performance management page.

  1. In the layout file of the app activity, create a button named TRIGGER ANR to trigger an ANR error.
  2. Add the following code to the MainActivity.java file to simulate an ANR error and call the initAnrTestButton function in the onCreate function in the MainActivity.java file:
    public void initAnrTestButton() { findViewById(R.id.anr_test).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("apmsAndroidDemo", "trigger anr"); anrTestEnable = true; } }); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (anrTestEnable) { try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } } return super.dispatchKeyEvent(event); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (anrTestEnable) { try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } } return super.dispatchTouchEvent(ev); }
  3. Tap the TRIGGER ANR button for several times until the pop-up indicating ANR is displayed.
  1. Add the code for calling APMS.enableCollection to enable performance data reporting when the APMS Collection ON button is tapped.
  2. findViewById(R.id.enable_apms_on).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { APMS.getInstance().enableCollection(true); } });
  3. Add the code for disabling performance data reporting when the APMS Collection OFF button is tapped.
  4. findViewById(R.id.enable_apms_off).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { APMS.getInstance().enableCollection(false); } });
  5. Pack and run the app, and tap Send Network Request to report a network event.
  1. Create two buttons named APMS ANR MONITOR ON and APMS ANR MONITOR OFF in the app activity layout file to enable and disable ANR monitoring, respectively.
  2. Tap APMS ANR MONITOR ON to call enableAnrMonitor to enable ANR monitoring.
  3. findViewById(R.id.enable_apms_on).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { APMS.getInstance().enableAnrMonitor(true); } });
  4. ANR monitoring is enabled by default. To disable it, tap APMS ANR MONITOR OFF.
  5. findViewById(R.id.enable_apms_off).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { APMS.getInstance().enableAnrMonitor(false); } });

    Package and run your app, and tap the TRIGGER ANR button to trigger an ANR error.

    Checking the Overview

    1. Sign in to AppGallery Connect and click My projects.
    2. Find your project and click and app for which you want to view performance data.
    3. Go to Quality > APM.
    4. Click the Overview tab. In the lower part of the page, you can view information about the network request duration in top 5 locations and network request success rate by time.

    Viewing Network Analysis

    1. Click the Network analysis tab. This tab page records the number of requests, response time, and request success rate of each URL. You can filter them by time.
    2. Click View details of a request. The request details page is displayed, containing the request duration and request success rate.
      On the Request duration page, the request duration distribution is displayed, and the request duration statistics are collected from different dimensions (version number, country/region, device model, level-1 region, system version, carrier, and network).
    3. On the Request success rate page, the status code distribution is displayed, and the request success rate statistics are collected from different dimensions (version number, country/region, device model, level-1 region, system version, carrier, and network).

    Viewing Custom Network Event Analysis

    1. There is no separate entry for viewing custom network event analysis data. The procedure for viewing the data is the same as that for viewing network analysis. If any property is set, you can view the request duration and request success rate of the property by clicking View details.

    Viewing Custom Event Analysis

    1. Click the App analysis tab. This tab page displays the list of reported custom events, including the custom event name, median value, number of samples, and the button for viewing details.
    2. Click View details next to CustomEvent1 to view the distribution of the time required for the custom event. Click the ProcessingTimes tab page to view the distribution of the ProcessingTimes measurement. The multi-dimensional analysis information is displayed at the bottom. You can check the distribution of ProcessingTimes under the custom properties Status and ProcessingResult.

    Viewing ANR Data

    1. Click the ANR analysis tab. The ANR report page is displayed. This page displays the ANR trend information, including top 5 problems in last 24 hours (sorted by affected-user rate), number of ANR occurrences, number of affected users, and affected-user rate distribution in different dimensions such as time, device model, OS version, and app version, as well as the list of ANR errors categorized by type.
    2. Click a card of a problem among the top 5 problems. The details page of this ANR error type is displayed, containing metrics such as the affected-user rate, ANR rate (number of ANR occurrences divided by number of app launches), number of occurrences, affected-user count trend over time, and affected-user count distribution by device model, app version, and OS version.
    3. Click View details next to a record in the Records list to view the details of the record.

    Well done. You have successfully created an app that integrates APS of AppGallery Connect and learned how to view and analyze app performance data on the app performance management page.

    For details about APM APIs, please refer to API Reference.

    Download the demo source code used in this codelab from the following address:

    Download source code

    Code copied