ZOFTINO.COM android and web dev tutorials

Firebase Performance Monitoring for Android

It is important to know how your app is performing on user devices in order to reduce number of uninstalls and improve user satisfaction because you may not have tested your app in terms of performance on different types of devices covering different versions of android and different manufacturers.

Firebase provides performance monitoring SDK. You can add that to your app so that it can capture performance data of your app. The captured performance data can be viewed in Firebase console. By analyzing the performance data, you can identify performance issues in your app and fix them.

Once you add Firebase performance monitoring SDK to your app, it will automatically capture performance data such as app startup time, background, foreground and https network time.

Adding Firebase Performance Monitoring SDK

To add Firebase performance monitoring SDK to your android project, first you need add Firebase SDK to your project. To add firebase to android from android studio, go to tools > firebase, in the assistant window, expand any one of the firebase feature listed, click get started link, then click connect and follow instruction to complete the setup.

To add Firebase sdk manually, please see adding firebase to android project and firebase analytics tutorial for detailed instructions.

Next, add firebase performance monitoring libraries to your project. Add below entries to your project level build.gradle file.

buildscript {
   
    repositories {
        google()
        jcenter()

    }
    dependencies {

	.....

        classpath 'com.google.firebase:firebase-plugins:1.1.5'

    }
}
. . .

Add below entries to app level gradle.build file.

apply plugin: 'com.android.application'
apply plugin: 'com.google.firebase.firebase-perf'

....

dependencies {

....

    implementation 'com.google.firebase:firebase-perf:11.8.0'

....

That’s it, after this setup, default performance metrics of your app will be captured by the performance monitoring tool without needing to add any code. But it takes 12 hours for the performance data to appear in firebase console.

Disabling Performance Monitoring

To disable performance monitoring, you can add below meta-data tag to your project AndroidManifest.xml file. To enable performance monitoring, set the tag to true.

 <meta-data android:name=firebase_performance_collection_enabled android:value=false /> 

To enable or disable firebase performance monitoring programmatically, get FirebasePerformance object and call setPerformanceCollectionEnabled method.

 FirebasePerformance.getInstance().setPerformanceCollectionEnabled(false); 

To permanently disable Firebase performance monitoring in your app, you can use below meta-data tag. If performance monitoring is disabled this way, it can’t be enabled programmatically.

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

Trace

A trace represents performance data between two points in code. Default traces capture time duration between when an app icon is clicked and it is opened, time duration that app spent in the background each time it goes to background, and time duration that app spent in the foreground each time it comes to foreground.

You can define custom traces to track performance metrics between two points in the code using FirebasePerformance object. First create FirebasePerformance object calling getInstance method. Then create Trace object by calling newTrace method on FirebasePerformance object passing trace identifier to the method. Then call start method on trace object in the code where you want to start capturing performance data for the trace. Then you need to call stop method on the trace object where you want to stop capturing performance data for the trace.

Below code instantiates and defines starting point for a trace.

 Trace addDbTrace = FirebasePerformance.getInstance().newTrace("add_record_realtime");
addDbTrace.start(); 

Below code defines ending point of the trace.

 addDbTrace.stop();

In between these two points in the code, you can add custom performance attributes to the trace. Attribute can be added to trace by calling putAttribute method on trace object passing attribute name and value. There is a limitation of 5 on the number of attributes that can be added to a trace.

Below code shows how to add custom attributes to firebase performance monitoring trace.

addTrace.putAttribute("userId", user.getUserId());

Below code shows adding firebase performance monitoring trace to realtime database call that adds data to db.

 private void addRecord(Record record) {
	final Trace addTrace = FirebasePerformance.getInstance().newTrace("add_rec_add");
	addTrace.start();
              addTrace.putAttribute("category", classifiedAd.getCategory());
              addTrace.putAttribute("phone", classifiedAd.getPhone());
	dbRef.child("records").child(rec.getId())
	.setValue(record)
	.addOnCompleteListener(new OnCompleteListener<Void>() {
		@Override
		public void onComplete(@NonNull Task<Void> task) {
			if (task.isSuccessful()) {     
				Log.d(TAG, "Record has been added to db");
			} else {
				Log.d(TAG, "Record couldn't be added to db");
			}
			addTrace.stop();
		}
	});
} 

If you want to count occurrence of some event or data condition during a trace, you can do so using incrementCounter method of trace object as shown below.

if(cart.priceyItems > 1){
    addTrace.incrementCounter("priceyItem", cart.priceyItems);
}

Adding Trace Using Annotation

You can use annotation to add trace to a method. But this way, you can’t add custom properties and counter.

@AddTrace(name = "viewDataFragment")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
}

Adding Performance Monitoring for HTTP Calls

Performance data is automatically captured for network calls. If some calls are missing or you want to add custom information to network performance report, you can add specific https calls to monitoring. To do that you need to first get HttpMetric object by calling newHttpMetric method on FirebasePerformance and then call start, putAttribute and stop methods as shown below.

 try {
    url = new URL("https://targeget/url");
    HttpMetric httpMetric =
            FirebasePerformance.getInstance().newHttpMetric(url,
                    FirebasePerformance.HttpMethod.GET);
    httpMetric.start();

    httpMetric.putAttribute("couponService", storeName);
    httpMetric.setRequestPayloadSize(request.size());
     //send http request
    sendHttpRequest(request);


    httpMetric.stop();
} catch (MalformedURLException e) {
    e.printStackTrace();
}
 

Firebase Performance Monitoring Reports

To view data captured by performance monitoring SDK, you need to login to firebase console, in the left navigation click performance in stability section to see performance monitoring dashbaorad. On the dashboard you can see traces by frequency report and app start trace median duration.

firebase performance monitoring firebase console reports dashboard

You can click view traces link or traces tab to view data for all traces.

firebase performance monitoring traces report example

You can click a trace to view performance details by country, OS, app version and device.

firebase performance monitoring trace-detail report