First of all you need to setup your project adding Firebase to your Android project following the steps described in this topic.
Add the FCM dependency to your app-level build.gradle
file
dependencies {
compile 'com.google.firebase:firebase-messaging:11.0.4'
}
And at the very bottom (this is important) add:
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
Add the following to your app's manifest:
A service that extends FirebaseMessagingService
. This is required if you want to do any message handling beyond receiving notifications on apps in the background.
A service that extends FirebaseInstanceIdService
to handle the creation, rotation, and updating of registration tokens.
For example:
<service
android:name=".MyInstanceIdListenerService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFcmListenerService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Here are simple implementations of the 2 services.
To retrieve the current registration token extend the FirebaseInstanceIdService
class and override the onTokenRefresh()
method:
public class MyInstanceIdListenerService extends FirebaseInstanceIdService {
// Called if InstanceID token is updated. Occurs if the security of the previous token had been
// compromised. This call is initiated by the InstanceID provider.
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Send this token to your server or store it locally
}
}
To receive messages, use a service that extends FirebaseMessagingService
and override the onMessageReceived
method.
public class MyFcmListenerService extends FirebaseMessagingService {
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String from = remoteMessage.getFrom();
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Map<String, String> data = remoteMessage.getData();
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// do whatever you want with this, post your own notification, or update local state
}
in Firebase can grouped user by their behavior like "AppVersion,free user,purchase user,or any specific rules" and then send notification to specific group by send Topic Feature in fireBase.
to register user in topic use
FirebaseMessaging.getInstance().subscribeToTopic("Free");
then in fireBase console, send notification by topic name
More info in the dedicated topic Firebase Cloud Messaging.