Firebase
Firebase has tools and infrastructures to build the app. It contains a lot of features, in this blog we will take a look at how to setting up Android application for receive notification from Firebase Cloud Messaging.
If you are using Google Cloud Messaging, Google recommended to upgrading FCM, because FCM is a new version of GCM.
Setup
First, go to Firebase console, log in your account then click to create a new project, fill your project name and region.
Click add Firebase to your Android app.
Add your package name and debug signing certificate SHA-1
.
You can see your SHA-1
by run following command.
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
Your bowser will download google-services.json
. It is a google service configuration. Move it into root directory in your app module.
Add Google Service plugin in build.gradle
in root of project, and sync your Gradle
.
Now, we’re finished setting up in Firebase console. We will move to next step, set up your Android project.
Add firebase messaging dependency in build.gradle
in app module. And sync Gradle
.
dependencies { // ... compile 'com.google.firebase:firebase-messaging:9.0.1' }
Add FirebaseInstanceIdService
for get FCM instance ID token from Firebase Cloud Messaging Server.
The onTokenRefresh
method called if token is updated.
When you get token from FCM. You can use it for persisting to your server.
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; @Override public void onTokenRefresh() { String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); sendRegistrationToServer(refreshedToken); } private void sendRegistrationToServer(String token) { // TODO: Send any registration to your app's servers. } }
Add FirebaseMessagingServer
for receive notification message from FCM.
The onMessageReceived called when the message is received. You have to handle the message from FCM here. Such as; Create and show notification bar.
public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { // Create and show notification sendNotification(remoteMessage.getNotification().getBody()); } private void sendNotification(String messageBody) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_ic_notification) .setContentTitle("FCM Message") .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } }
After that add the both classes as a service in AndroidManifest.xml
.
The both services are running on background.
<service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> <service android:name=".MyFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service>
Now, you are finished to set up the Android application.
Build and run it.
You will see FCM InstanceID token in logcat
. Because we log it in onTokenRefresh
method. Copy it.
New FCM feature that GCM does not have, that is we can send notification message directly from Firebase console, that’s cool! right?
Open Firebase console and select Notification menu on the left-hand side.
Look at the target section. We can send the message to device three ways.
First, send to all devices in a specific application.
Second, send to a device that subscribe to the topic.
In the first time, your project does not have any topic. You need to subscribe the topic in your project.
By call following method.
FirebaseMessaging.getInstance().subscribeToTopic("news");
waiting about one day delay between new topic creation, it will be available in your Firebase console.
And the last, send to a specific device by FCM registration token, that show in your logcat
above.
In Advance options, you can custom your message title and can attach custom data (key/value pair). Also, can set a priority of the message and enable/disable sound when your device receives the message. And you set how long of the message that should be kept for resending, default are 4 weeks.
You can handle the custom data when notification message is tapped. Custom data of notification message is available in the intent extras.
if (getIntent().getExtras() != null) { for (String key : getIntent().getExtras().keySet()) { String value = getIntent().getExtras().getString(key); Log.d(TAG, "Key: " + key + " Value: " + value); } }
Above code we check that custom data is exist or not, then for each all key of custom data, then get value of data by key.
Send first notification message
Put your message text and click send the message.
Add some custom data, then click SEND MESSAGE.
Waiting a few minutes, you will receive notification on your Android application.
Tap it! The custom data will show up in Logcat
.
Yeah!, now we completed setup Android application to receive notification from Firebase console. You can download source code on Github.
Reference: Firebase document
hi there if i have multiple notification send in background so how do i save them all in my desired location (i.e: database /list) ,by only clicking on one notification of the many background notification sent on the device by the server which are in the notification/system tray
Very useful thank you.
I’m trying just to get the simple notification going so I added only the firebase-core dependency but the
notification does not show up … did you have a similar problem, or any idea what I’m missing, thank you!
sir great tutorial there
but im getting error, it says background sync failed: AUTHENTICATION_FAILED
any help please?
how to use color image icon in push notification —target sdk version above 20
Hey I am so happy I found your weblog, I really found you by mistake, while I was browsing on Askjeeve for something else, Anyways I
am here now and would just like to say thank you for a incredible post and a all round entertaining
blog (I also love the theme/design), I don’t have time to go through it all at the minute but I
have book-marked it and also included your RSS feeds, so
when I have time I will be back to read a lot more,
Please do keep up the awesome b.
Sir can you please describe how to turn on and off the notification using the image switchers?