To add analytics to an Android project using Firebase Cloud Messaging (FCM), you would integrate Firebase Analytics. FCM and Firebase Analytics together help you gain insights into how users interact with your app, especially with notifications. Here’s how to set it up:
1. Set Up Firebase in Your Android Project
- Create a Firebase Project:
- Go to the Firebase Console, create a project, and add your Android app to the project.
- Add the Firebase SDK:
- Download the
google-services.json
file for your app and place it in theapp
directory.
dependencies {
classpath 'com.google.gms:google-services:4.3.15'
}
- Update the app-level
build.gradle
file:
apply plugin: 'com.google.gms.google-services'
dependencies {
implementation 'com.google.firebase:firebase-messaging:23.2.0'
implementation 'com.google.firebase:firebase-analytics:21.3.0'
}
2. Implement Firebase Analytics in Your App
- Initialize Firebase Analytics:
In your mainActivity
orApplication
class:
import com.google.firebase.analytics.FirebaseAnalytics;
public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize Firebase Analytics
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
}
}
- Log Events:
Firebase Analytics provides several predefined events. For example, to log a custom event for notification opens:
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "notification_opened");
mFirebaseAnalytics.logEvent("notification_interaction", bundle);
3. Enable FCM Data in Firebase Analytics
When you use FCM in conjunction with Firebase Analytics, notification-related events like notification_received
and notification_open
will be tracked automatically if analytics is enabled. Make sure that:
- FCM Automatic Data Collection is enabled:
FirebaseMessaging.getInstance().setAutoInitEnabled(true);
4. Monitor Notifications in Firebase Console
You can view metrics like the number of times notifications were opened, conversion events, and more under Analytics and Notifications in the Firebase Console.