Get started with Performance Monitoring for Android

Before you begin

If you haven't already, add Firebase to your Android project.

Step 1: Add Performance Monitoring to your app

  1. In your module (app-level) Gradle file (usually app/build.gradle):

    • Add the Performance Monitoring Gradle plugin.
    • Add the dependency for the Performance Monitoring Android library.
    apply plugin: 'com.android.application'
    // Apply the Performance Monitoring plugin to enable instrumentation
    apply plugin: 'com.google.firebase.firebase-perf'
    
    dependencies {
        // ...
    
        implementation 'com.google.firebase:firebase-core:16.0.8'
    
        // Add Performance Monitoring dependency line
        implementation 'com.google.firebase:firebase-perf:16.2.5'
    }
    
  2. In your root-level (project-level) Gradle file (build.gradle), add the rules to include the Performance Monitoring plugin.

    buildscript {
    
        repositories {
          // Check that you have the following line (if not, add it):
          jcenter()
    
          // ...
        }
    
        dependencies {
          // ...
          classpath 'com.google.gms:google-services:4.2.0'  // Google Services plugin
    
          // Add the following line:
          classpath 'com.google.firebase:perf-plugin:1.2.0'  // Performance Monitoring plugin
        }
    }
    
  3. Recompile your app.

Firebase is now monitoring automatic traces and HTTP/S network requests.

Step 2: Check the Firebase console for Performance Monitoring results

  1. Build your app in Android Studio.

  2. Test your app using either:

    • An Android emulator with a recent image and Google Play services 15.0.0 or later

    • A test device with Google Play services 15.0.0 or later.

  3. Confirm that Performance Monitoring results display in the Firebase console.

    Results usually display within 12 hours.

Step 3: (Optional) Add custom traces and custom metrics

A custom trace is a report of performance data associated with some of the code in your app. To learn more about custom traces, see the Performance Monitoring overview.

You can have multiple custom traces in your app, and it's possible to have more than one custom trace running at a time. Each custom trace can have one or more metrics to count performance-related events in your app, and those metrics are associated with the traces that create them.

  1. Import these Performance Monitoring classes at the top of your .java or .kt file:

    import com.google.firebase.perf.FirebasePerformance;
    import com.google.firebase.perf.metrics.Trace;
    
  2. Just before the code where you want to start a trace in your app, add the following line of code to start a trace called test_trace:

    Java
    Android

    Trace myTrace = FirebasePerformance.getInstance().newTrace("test_trace");
    myTrace.start();

    Kotlin
    Android

    val myTrace = FirebasePerformance.getInstance().newTrace("test_trace")
    myTrace.start()
  3. To count performance-related events that occur in your app (such as cache hits and misses), add lines of code similar to the following each time that the event occurs. Use a string other than item_cache_hit or item_cache_miss to name that event if you're counting a different type of event:

    Java
    Android

    Item item = cache.fetch("item");
    if (item != null) {
        myTrace.incrementMetric("item_cache_hit", 1);
    } else {
        myTrace.incrementMetric("item_cache_miss", 1);
    }

    Kotlin
    Android

    val item = cache.fetch("item")
    if (item != null) {
        myTrace.incrementMetric("item_cache_hit", 1)
    } else {
        myTrace.incrementMetric("item_cache_miss", 1)
    }
  4. Just after the code where you want to stop your trace, add the following line of code:

    Java
    Android

    myTrace.stop();

    Kotlin
    Android

    myTrace.stop()

Step 4: (Optional) Trace specific methods using @AddTrace

You can add the @AddTrace annotation to methods in your app and provide a string to identify the resulting trace. This causes a trace to start at the beginning of this method and to stop when the method completes.

Note, though, that traces created in this way do not have metrics available.

For example, to create a trace called onCreateTrace that runs when the onCreate() method is called, use code similar to the following:

Java
Android

@Override
@AddTrace(name = "onCreateTrace", enabled = true /* optional */)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

Kotlin
Android

@AddTrace(name = "onCreateTrace", enabled = true /* optional */)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
}

Step 5: (Optional) Add monitoring for specific network requests

Performance Monitoring collects network requests automatically. Although this includes most network requests for your app, some might not be reported.

To include custom network requests in Performance Monitoring, add the following code to your app:

Java
Android

HttpMetric metric =
        FirebasePerformance.getInstance().newHttpMetric("https://www.google.com",
                FirebasePerformance.HttpMethod.GET);
final URL url = new URL("https://www.google.com");
metric.start();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
try {
    DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
    outputStream.write(data);
} catch (IOException ignored) {
}
metric.setRequestPayloadSize(data.length);
metric.setHttpResponseCode(conn.getResponseCode());
printStreamContent(conn.getInputStream());

conn.disconnect();
metric.stop();

Kotlin
Android

val metric = FirebasePerformance.getInstance().newHttpMetric("https://www.google.com",
        FirebasePerformance.HttpMethod.GET)
val url = URL("https://www.google.com")
metric.start()
val conn = url.openConnection() as HttpURLConnection
conn.doOutput = true
conn.setRequestProperty("Content-Type", "application/json")
try {
    val outputStream = DataOutputStream(conn.outputStream)
    outputStream.write(data)
} catch (ignored: IOException) {
}

metric.setRequestPayloadSize(data.size.toLong())
metric.setHttpResponseCode(conn.responseCode)
printStreamContent(conn.inputStream)

conn.disconnect()
metric.stop()

The HTTP/S network requests that you specifically capture in this way appear in the Firebase console along with the network requests that Performance Monitoring captures automatically.

Step 6: Deploy your app then review results

After you've validated Performance Monitoring using one or more test devices, you can deploy the updated version of your app to your users.

You can monitor performance data in the Firebase console.

Known issues

  • The Performance Monitoring Gradle plugin v1.1.0 can cause a mismatch in Guava dependencies, resulting in the following error:

    Error:Execution failed for task ':app:packageInstantRunResourcesDebug'.
    > com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;

    If you see this error, you can either:

    • Upgrade the Performance Monitoring plugin to v1.1.1 or later (the most recent is v1.2.0).

    • Replace the Performance Monitoring plugin dependency line in your root-level (project-level) Gradle file (build.gradle), as follows:

      buildscript {
        // ...
      
        dependencies {
          // ...
      
          // Replace the standard Performance Monitoring plugin dependency line, as follows:
          classpath ('com.google.firebase:perf-plugin:1.1.0') {
                      exclude group: 'com.google.guava', module: 'guava-jdk5'
          }
        }
      }
      
  • Performance Monitoring only supports monitoring HTTP/S network requests made using the OkHttp HTTP client v3.x.x.

  • Performance Monitoring reports the total payload size for HTTP/S network requests based on the value set in the HTTP content-length header. This value might not always be accurate.

  • Performance Monitoring only supports the main process in multi-process Android apps.

  • The Performance Monitoring Gradle plugin is not compatible with the following:

    • DexGuard, which disables automatic traces and HTTP/S network request monitoring. However, custom traces added using the Performance Monitoring SDK behave normally if your app uses DexGuard.

    • Jack, which is deprecated.

Debug your integration

You can enable debug logging for Performance Monitoring at build time, by adding a <meta-data> element to your app's AndroidManifest.xml file, like so:

<application>
    <meta-data
      android:name="firebase_performance_logcat_enabled"
      android:value="true" />
</application>

You can view trace and HTTP/S network request logging using logcat filtering. Performance Monitoring log messages are tagged with FirebasePerformance, and you can filter them using following command:

adb logcat -s FirebasePerformance

Next steps

Feedback verzenden over...

Hulp nodig? Ga naar onze ondersteuningspagina.