Get 20% off all New HostGator Hosting plans with Coupon: SNAPPY.
Android Tutorials : Firebase Push Notification Tutorial
Firebase cloud messaging (FCM) is a new version of Google Cloud Messaging (GCM). Using FCM you can send notification messages to your client application in order to drive user engagement. With FCM, you can send two types of messages to the client app: Notification messages and Data messages, A notification message is the more lightweight option, with a 2KB limit and a predefined set of user-visible keys. Data messages let developers send up to 4KB of custom key-value pairs. Notification messages can contain an optional data payload, which is delivered when users tap on the notification. Use notification messages when you want Firebase cloud messaging (FCM) to handle displaying a notification on your client app’s behalf. Use data messages when you want to process the messages on your client app.
Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded (still running) apps to receive notification messages or data messages, you’ll need to write code to handle the onMessageReceived callback. In the overridden method FirebaseMessagingService.onMessageReceived(…), you can get the message data from the received message and perform the desired action according to the needs of your android app.
So to receive messages, you should use a service that extends FirebaseMessagingService. Your service should override the onMessageReceived callback. The method onMessageReceived(…) will not get called if the app is in background or killed state, when the message is sent through Firebase Console. But when the message is sent via API (perform a POST to the following URL : https://fcm.googleapis.com/fcm/send ), the method onMessageReceived(…) will get invoked. So in this tutorial we will be sending messages via Firebase console as well as via API.
Now let us create an Android application to which we can send push notifications using Firebase Notifications. The steps will be described in five detailed yet simple parts.
Part ! : Includes steps to create a new Android application and set up Firebase in it.
1. Create a new Android Project in Android Studio. Give it a name and select the Minimum SDK on which your app will run on. I chose API 16 : Android 4.1 (JELLY_BEAN).
2. When you are prompted to add an activity to your application choose Blank Activity and click on next button.
3. In the next step click on Finish and in few seconds your application should be loaded in Android Studio.
4. Open build.gradle(Module:App) file of your application and add the following dependencies inside dependencies section of build.gradle (Module:App) file.
1 2 3 4 5 6 7 8 9 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.google.firebase:firebase-core:9.4.0' compile 'com.google.firebase:firebase-messaging:9.4.0' compile 'com.google.android.gms:play-services-auth:9.4.0' } |
5. Now add the packagingOptions directive to your build.gradle(Module : App) file as shown below. This is how your build.gradle (Module : App) will look now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.androidbash.androidbashfirebasepushnotify" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.google.firebase:firebase-core:9.4.0' compile 'com.google.firebase:firebase-messaging:9.4.0' compile 'com.google.android.gms:play-services-auth:9.4.0' } apply plugin: 'com.google.gms.google-services' |
6. The application requires following permissions to work. Your app might not work unless you add these permissions to your AndroidManifest.xml file.
1 |
<uses-permission android:name="android.permission.INTERNET"/> |
Part !! : Includes Firebase account creation and getting google-services.json file from Firebase console
1. The first thing you need to do to get started with Firebase is sign up for a free account. You can use your Google account to sign in to your firebase account.
2. After clicking on ‘Sign In with Google’ you will be asked to allow the Firebase to view your Email and your basic profile. Click on Allow button to continue.
3. Once you are signed in, Click on Go to your Console button if you are not automatically redirected to your firebase console. Click on Create New Project button in your firebase console.
4. Now you can see an overview of your new Firebase project. Now click on Add Firebase to your Android App as shown below.
5. Now you need to enter your App details (your application’s package name) and also get SHA-1 finger print and paste it in the field as shown below.
Click on Add App button. Upon clicking it, a file named google-services.json gets downloaded to your machine.
Note : Following image shows how to get SHA-1 from Android Studio.
6. Copy the google-services.json file and paste in the app folder of your Android application.
Note: If you forget to copy and paste google-services.json file you will get the following error when you build your app.
7. Open the build.gradle (project level) file of your android application and add classpath ‘com.google.gms:google-services:3.0.0’ in the dependencies section. Your build.gradle (project level) file will look as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() mavenLocal() } dependencies { classpath 'com.android.tools.build:gradle:1.3.0' classpath 'com.google.gms:google-services:3.0.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() mavenLocal() } } |
8. Now add apply plugin: ‘com.google.gms.google-services’ at the bottom of your build.gradle (App level) file, just below dependencies section. Also check whether you have added the following dependencies in the dependencies section of build.gradle (App level). Click on sync now or re-build the android application.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.google.firebase:firebase-core:9.4.0' compile 'com.google.firebase:firebase-messaging:9.4.0' compile 'com.google.android.gms:play-services-auth:9.4.0' } apply plugin: 'com.google.gms.google-services' |
9. The following section in the Firebase console shows the overview of your project. Click on Notifications button in the left menu to go to Notifications tab of your Firebase console. Before you send your first notification, let us code our android app to handle Firebase Notifications.
Part !!! : Includes modifications to build.gradle file and other XML files
1. At this point of time, the build.gradle (Module:app) file should look like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.androidbash.androidbashfirebasepushnotify" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.google.firebase:firebase-core:9.4.0' compile 'com.google.firebase:firebase-messaging:9.4.0' compile 'com.google.android.gms:play-services-auth:9.4.0' } apply plugin: 'com.google.gms.google-services' |
2. And also, the build.gradle (Module:project) file should look like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { mavenLocal() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.3.0' classpath 'com.google.gms:google-services:3.0.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() jcenter() } } |
2. In order to use Firebase notification, open your AndroidManifest.xml and add the following under application tag.
1 2 3 4 5 6 7 8 9 10 11 12 |
<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> |
3. Create colors.xml file in the values folder and add the following code. You can change the colors to change the look of the application.
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="primary">#2196F3</color> <color name="primary_dark">#1976D2</color> <color name="primary_light">#BBDEFB</color> <color name="accent">#03A9F4</color> <color name="primary_text">#FFFFFF</color> <color name="secondary_text">#727272</color> <color name="icons">#FFFFFF</color> <color name="divider">#B6B6B6</color> </resources> |
4. The menu_main.xml file in the menu folder looks like this. Menu includes a sign out button in it.
1 2 3 4 5 6 |
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <item android:id="@+id/action_settings" android:title="@string/action_settings" android:orderInCategory="100" app:showAsAction="never" /> </menu> |
5. The styles.xml file in the values folder looks like this.
1 2 3 4 5 6 7 8 9 10 |
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/primary</item> <item name="colorPrimaryDark">@color/primary_dark</item> <item name="colorAccent">@color/accent</item> </style> </resources> |
6. The strings.xml file in the values folder looks like this. Always keep a habit of including all your xml string resources in this file.
1 2 3 4 5 6 7 |
<resources> <string name="app_name">AndroidBashFirebasePushNotify</string> <string name="action_settings">Settings</string> <string name="main_activity">This is our Main Activity</string> <string name="another_activity">This is our Another Activity</string> </resources> |
Part !V : Includes creation of new XML layout files and modification to activity_main.xml file
1. Create a new XML layout resource file and name it as activity_another.xml. It includes an Imageview and a Textview in it. The activity_another.xml file of our application has the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".AnotherActivity"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:layout_gravity="center_horizontal" android:src="@drawable/firebase_icon" /> <TextView android:id="@+id/informationTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_horizontal" android:text="@string/another_activity" /> </LinearLayout> |
2. The acivity_main.xml includes an ImageView and TextView. The acivity_main.xml has the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:layout_gravity="center_horizontal" android:src="@drawable/firebase_icon" /> <TextView android:id="@+id/informationTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_horizontal" android:text="@string/main_activity" /> </LinearLayout> |
Part V : Includes creation of new Java classes and modification to MainActivity.java file
1. Create a new java class in your package and name it as AnotherActivity.java. This is a simple Activity class which gets opened when the user taps on a notification message which includes a key named as “AnotherActivity”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.androidbash.androidbashfirebasepushnotify; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; /** * Created by AndroidBash on 20-Aug-16. */ public class AnotherActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_another); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } |
2. Now create another new java class and name it as MyFirebaseInstanceIDService.java. It extends FirebaseInstanceIdService class and contains an overridden method onTokenRefresh(). This method is called if InstanceID token is updated. This may occur if the security of the previous token had been compromised. Note that this is called when the InstanceID token is initially generated so this is where you would retrieve the token. This class has the following code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.androidbash.androidbashfirebasepushnotify; /** * Created by AndroidBash on 20-Aug-16. */ import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the InstanceID token * is initially generated so this is where you would retrieve the token. */ // [START refresh_token] @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. sendRegistrationToServer(refreshedToken); } // [END refresh_token] /** * Persist token to third-party servers. * * Modify this method to associate the user's FCM InstanceID token with any server-side account * maintained by your application. * * @param token The new token. */ private void sendRegistrationToServer(String token) { // TODO: Implement this method to send token to your app server. } } |
3. Now create another java class and name it as MyFirebaseMessagingService.java. It extends FirebaseMessagingService. It contains an overridden method onMessageReceived(RemoteMessage remoteMessage). If you want foregrounded (still running) apps to receive notification messages or data messages, you’ll need to write code to handle the onMessageReceived callback. The method onMessageReceived(…) will not get called if the app is in background or killed state, when the message is sent through Firebase Console. But when the message is sent via API (perform a POST to the following URL:https://fcm.googleapis.com/fcm/send ), the method onMessageReceived(…) will get invoked. We will be showing both the ways to send notification. This class has the following code in it. Please go through the comments written in the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
package com.androidbash.androidbashfirebasepushnotify; /** * Created by AndroidBash on 20-Aug-16. */ import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "FirebaseMessageService"; Bitmap bitmap; /** * Called when message is received. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { // There are two types of messages data messages and notification messages. Data messages are handled // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app // is in the foreground. When the app is in the background an automatically generated notification is displayed. // When the user taps on the notification they are returned to the app. Messages containing both notification // and data payloads are treated as notification messages. The Firebase console always sends notification // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options // Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } //The message which i send will have keys named [message, image, AnotherActivity] and corresponding values. //You can change as per the requirement. //message will contain the Push Message String message = remoteMessage.getData().get("message"); //imageUri will contain URL of the image to be displayed with Notification String imageUri = remoteMessage.getData().get("image"); //If the key AnotherActivity has value as True then when the user taps on notification, in the app AnotherActivity will be opened. //If the key AnotherActivity has value as False then when the user taps on notification, in the app MainActivity will be opened. String TrueOrFlase = remoteMessage.getData().get("AnotherActivity"); //To get a Bitmap image from the URL received bitmap = getBitmapfromUrl(imageUri); sendNotification(message, bitmap, TrueOrFlase); } /** * Create and show a simple notification containing the received FCM message. */ private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("AnotherActivity", TrueOrFalse); 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) .setLargeIcon(image)/*Notification icon image*/ .setSmallIcon(R.drawable.firebase_icon) .setContentTitle(messageBody) .setStyle(new NotificationCompat.BigPictureStyle() .bigPicture(image))/*Notification with Image*/ .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } /* *To get a Bitmap image from the URL received * */ public Bitmap getBitmapfromUrl(String imageUrl) { try { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(input); return bitmap; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } } |
4. Open MainActivity.java and add the following code in it. It has a method named subscribeToPushService(). This method is invoked every time the user opens your app. This is where the user subscribes to notifications. MainActivity is the default activity which gets opened when the user taps on the received notification. But once the MainActivity is loaded we check for a key named “AnotherActivity” in the intent data that is passed to it. If the value of the key equals “True” then we are redirecting the application to AnotherActivity.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
package com.androidbash.androidbashfirebasepushnotify; /** * Created by AndroidBash on 20-Aug-16. */ import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessaging; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // If a notification message is tapped, any data accompanying the notification // message is available in the intent extras. In this project the launcher // intent is fired when the notification is tapped, so any accompanying data would // be handled here. If you want a different intent fired, set the click_action // field of the notification message to the desired intent. The launcher intent // is used when no click_action is specified. // // Handle possible data accompanying notification message. if (getIntent().getExtras() != null) { for (String key : getIntent().getExtras().keySet()) { String value = getIntent().getExtras().getString(key); if (key.equals("AnotherActivity") && value.equals("True")) { Intent intent = new Intent(this, AnotherActivity.class); intent.putExtra("value", value); startActivity(intent); finish(); } } } subscribeToPushService(); } private void subscribeToPushService() { FirebaseMessaging.getInstance().subscribeToTopic("news"); Log.d("AndroidBash", "Subscribed"); Toast.makeText(MainActivity.this, "Subscribed", Toast.LENGTH_SHORT).show(); String token = FirebaseInstanceId.getInstance().getToken(); // Log and toast Log.d("AndroidBash", token); Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } |
5. Finally here is how your AndroidManifest.xml should look.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidbash.androidbashfirebasepushnotify" > <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".AnotherActivity" android:label="@string/app_name" > </activity> <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> </application> </manifest> |
That’s it. Run the application to subscribe to Firebase push notifications. Now you can start sending notifications to all the subscribed users.
Here is how you send Push notifications along with image.
We will be showing 2 ways to send notifications.
1. Using Firebase console : Go to the overview section of your Firebase console and click on Notifications button on the left menu. Notification tab gets opened as shown below. Click on Send your First Message button. Enter the details of your push message in the fields provided.
We have included three key-values pairs [(image->https://ibin.co/2t1lLdpfS06F.png) & (AnotherActivity->True) & (message-> “AndroidBash First Push message”)] in the message as shown in the image below.
Verify the details and click on send button.
When sent using Firebase console, if the app is in the foreground then onMessageReceived() method will be called. Hence a notification with image an fetched from the url is displayed to the user (As shown in the Result 1 ). But if the app is background or killed state then onMessageReceived() method will not be called. Hence a simple notification containing just a message will be displayed in the notification bar of your android device. (As shown in the Result 2).
Result 1
Result 2
2. Using Messaging API : To send a message using API, you can use a tool called AdvancedREST Client, its a chrome extension, and send a message with the following parameters.
1 2 3 4 5 6 7 8 9 10 11 |
https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIza************adrTY { "data": { "image": "https://ibin.co/2t1lLdpfS06F.png", "message": "Firebase Push Message Using API" "AnotherActivity": "True" }, "to" : "f25gYF3***********************HLI" } |
Authorization key can be obtained by visiting Google developers console and click on Credentials button on the left menu for your project. Among the API keys listed, the server key will be your authorization key.
And you need to put tokenID of the receiver in the “to” section of your POST request sent using API. You can get the tokenID when you run your android app. We log the tokenID in the subscribeToPushService() method of the MainActivity.
When the notification is sent using API, onMessageReceived() method will be called whether or not the application is in foreground. The following image shows the result of the notification sent using API.
You can download the project and add your google-services.json file (downloaded from Firebase console of your Firebase App) under app folder and try it out.
If you have liked our tutorial, you can help us keep this website free for all Android enthusiasts either by buying our Android application from Google Play Store : Trailers Now Pro or by donating any small amount on my PayPal account. If you have followed our tutorial please do let us know by commenting below. It makes us write more and more articles on android application development. In case if you get stuck somewhere please do comment below and let us know. We usually reply within a day.
Get 20% off all New HostGator Hosting plans with Coupon: SNAPPY.
Note : Do not forget to :
Add google-services.json file under “app” folder.
Update Google Play Services and Google Repository to the latest versions available.
Get SHA-1 finger print and paste it during the creation of your firebase project.
Add all the required dependencies in the build.gradle file of your application.
hiii…i want to image without another activity key how i get image in notification.?
and i want to give some parameter like bday date and how i acess mysql database in console..?
Hello Jaydip, You can send any number of key-value pairs from Firebase console or using messaging API. You can retrieve the values in onMessageReceived(RemoteMessage remoteMessage) method of MyFirebaseMessagingService class.
Thanks alot.. It was clear explanation with comments… keep it up..
I have a problem. I get notification with icon while app is in foreground but when app is in background the notification is received but the icon and notification sound is missing. I think onMessageReceived() is not called when the application is in background. I tried many solution found on the web but still the problem persists.
Yes Dadhi. onMessageReceived() is not called when the app is in background if you are using Firebase console to send a Push message. So you need to send Push message from “Messaging-API” as explained in the tutorial. If you send the Push notification from “Messaging-API” then onMessageReceived() will be called. Make sure you set the notification sound inside onMessageReceived().
How i am finding that tutorial
I’m facing the same issue. When the app is in background, the image doesn’t appear in the notification drawer
Hello Shraddha , Did you use Firebase console to send push message? Or Messaging API?
I am using the Messaging API and have everything working:
(1) Push notification received with title and text
(2) Onclick, open app, launch activity and display image in imagview from ‘image’ key in the received push notification
The thumbnail is not working from the Messaging API. I’ve tried small images (e.g. 10kb), but no luck. Any help would be appreciated! The below is
var body = {
to: ‘/topics/test’,
priority: ‘high’,
notification: {
title: ‘test’,
text: ‘testing’,
image: ‘http://avatarbox.net/avatars/img32/test_card_avatar_picture_88303.jpg’
},
data: {
title: ‘test’,
text: ‘testing’,
image: ‘http://avatarbox.net/avatars/img32/test_card_avatar_picture_88303.jpg’
}
};
var bodyStringified = JSON.stringify(body);
// Set up the request
var post_req = http.request(options, function(res) {
res.setEncoding(‘utf8’);
res.on(‘data’, function (chunk) {
console.log(‘Response: ‘ + chunk);
});
});
Hello Gary,
I have 2 questions (assuming these are small for you) as I understood you already achieved them.
(1) Let’s assume, I am using second approach, I mean using Messaging API (ARC), How can I show Title and Message both in Notification Bar (Still we are getting our message as Title content in Notification Bar)… As you can see in screenshot : https://goo.gl/n2rn1B (due to this, we are getting incomplete message, because in Notification Bar title has limit maximum 1 line)
(2) Is it not possible for us to show notification’s message in AnotherActivity, whenever we do tap on Notification.
Please let me know the solution (exactly what and where I have to make changes in our code), as you already worked on these things.
And finally how our Messaging API should look like….
Thanks
Sir I tried this using your tutorial in my app , everything goes right , but iam facing one issue, that is when I launch my app for the 1st time , it is force closing leaving a msg ” Unfortunately App has been stopped” , and from second launch its working fine. please help me in fixing this.
Hello Rohith, Can you please post your logcat message? When an exception is thrown it will be logged in the logcat as an Error message. You can paste your logcat message on http://pastebin.com and give me a pastebin link to your file.
I think your token has not been ready for the very first time.
Very Well Explained. Only 1 problem Through API i am able to send image push notification to a single user. Is there anyway to send image push notification to all app users
Yes we can send notifications to all the users of the app. Follow this tutorial : http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
still the issue not solved
Thanks,
I solved my problem by referring your tutorial.
Really nice work,
keep it up.
waiting for more
onMessageReceived() not called when app in Background and i have tried “Messaging-API”, it give 200 status code but i did not get notification also? how can i get image in notification when app in background?
sir now onMessageReceived() called when app is background but when i use our database(Console) then app in background , onMessageReceived() not called from console, which code require in server side? when i use “Messaging-API” , onMessageReceived() called but from console it doesn’t work.
Everything is working perfectly, but I am not getting any image in the notification. I sending notification using api plugin u have mentioned.
It should work actually. Can you please try again and also please cross check the image link again.
Thanks for a step to step explanation. 🙂
That worked like charm! Thank you so much!
Nice tutorial! I just want to ask if it is possible for Firebase push notifications be trigged in my Android app? Here’s a scenario. I have an app that has registration and log in for users. I want to send a notification when the user is already registered in the app, then a simple notification will appear that says “Welcome! You are now registered.” Is this possible on Android Firebase? Thanks for your help.
If you want to display just this text whenever a user completes registration then it can be done by creating a notification. Please refer this link to create a simple notification. You need not use Firebase notification for this i guess. Thank you.
I need only data payload from firebase not a notification ,is it possible ???
Bcz when I send from firebase along with key n value pair …I got two notification …first from firebase notification n otherone is my app responsible to data payload to open image notification..so I need only data payload from firebase
Hello,
I followed every single (except adding SHA-1 to google-service.json) step, but i can not receive messages that was sent from the firebase console.
Hello Ahmet, Can you please tell me the error that is being displayed in log? Also please follow all the steps in the tutorial. Please try to add SHA1 and re-download google-services.json. Thank You!
Hi,
After i wrote above, i have updated android studio and suddenly everything worked…
thanks a lot 🙂
Glad it helped:)
Hi…can you please explain how this can be done with the topic option in the Firebase console.
Sure Nivedita:) I will try. Please give me some time. Thank You!
Hello,
I have followed your tutorial about Firebase Push Notifications.
It’s very well explained and works perfectly.
I just have a little problem, the notifications when app is closed work only after the second launch (and the others) and not after the first one. Do you have any idea why ?
Thank you so much.
I am following your tutorial , every goes right , I have a small query like ” how can I change msg text font size in on message recieved method ” is that possible, if possible please help me in doing this.
This is best tutorial for me
Thank You very much Deepa! Glad you liked it:)
is it possible to send image notification if the app is in foreground?? using Firebase console??
Hi thank you for this tutorial.I have one issue once the app is killed i am able to receive image ,from both notification payload and data payload.if app is in background i can receive but once its closed i am not able to receive.
Hi Sachin, As mentioned in the tutorial as of now you need to send Push notification using Messaging API in order to work during Killed state of your app. The method onMessageReceived(…) will not get called if the app is in background or killed state, when the message is sent through Firebase dashboard. But when the push message is sent via API (perform a POST to the following URL : https://fcm.googleapis.com/fcm/send ), the method onMessageReceived(…) will get invoked.
Thanks for sharing. I ‘m running in a scenario where I need to integrate FCM with 3rd party XMPP server. Integration done and message also coming from both channel as expected. But if I do logout from XMPP server that mean user logout for device, it still send me message from FCM channel. That mean FCM channel not getting logout. Could you please take some time to tell is there way to tell FCM-logout.
I wonder how to handle such scenario in case if user do logout from without any internet dependency.
Hello Shubham, As of now I am not aware of what you are asking for. I will get back to you in few days. Let me know if you have already achieved what you were looking for. Thank You!
my app is working fine but i am not getting notification. its showing completed in firebase console but not coming on my phone
hello sir,
i can’t get image in notification drawer…am using firebase notification service..please help me
Hello Aravindhan, Are you still facing the issue?
got solution sir
Thanks for your wonderful tutorial..
Thanks a lot perfect example
Thank you for the article my friend. 🙂
Tire-me uma dúvida: Já que no JSON enviado tem o parâmetro “AnotherActivity” setado “true”, por que você passa o mesmo parâmetro como extras da intent?
Hello Francis Rodrigues, Yes no need of it actually as we are not doing anything in “AnotherActivity”. Thank You:)
HI, I have implement your code! it’s working. But when notification comes image and test are displaying blank. Can you please share solution as soon as possible??
Hi Neha, This code is working fine for me now also. Images wont get downloaded when there is a network issue. Please double check if you have missed something. Let me know once you try.
Hello, Can you please guide me to validate the image field? If I use API call and I don’t send image field, the notification display a blank space below the message title. I need both cases, with image (which is working great) and without it.
Thanks in advance
I am calling from API but no any notification is received.
Is it because I have not added SHA1 because I have SHA1 conflict ?
Hi buddy. Great start for my own implementation of push notifications.
Really thank you!!
Glad you liked it. Thank You for your support.
hi
i get the error when running the apps???
can u help me solve it
thank you
04-07 02:26:58.623 24661-24661/com.example.hp.notificarion_firebase E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hp.notificarion_firebase, PID: 24661
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hp.notificarion_firebase/com.example.hp.notificarion_firebase.MainActivity}: java.lang.NullPointerException: println needs a message
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Caused by: java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at com.example.hp.notificarion_firebase.MainActivity.subscribeToPushService(MainActivity.java:58)
at com.example.hp.notificarion_firebase.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
04-07 02:26:58.636 24661-24661/com.example.hp.notificarion_firebase I/Process: Sending signal. PID: 24661 SIG: 9
Hi, If u have any println statements or log messages in your MainActivity, just remove them and run the app.
thank you
remove this part coding from mainactivity as show in below
apps can running
but when i use firebase notification send messange , my phone has receive but didnt show the messange …
how can solve this problem
and i remove the coding part ..
Does it cause the problem come out ??
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals(“AnotherActivity”) && value.equals(“True”)) {
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra(“value”, value);
startActivity(intent);
finish();
}
}
}
subscribeToPushService();
Thanks for the tips diplaying image on notification
I implemented the way you call the image url and it work
But, there is one problem
Before I added the image to notification, My notification was still displaying the content of notificaton.
code like this:
builder.setContentText(pesan);
and when I add your code to set image, the content disappear.
Is it possible to keep both of them show?
Same problem. Any solution?
Hello sir, I am using firebase messaging service for my android app, but I am facing a problem(tested in lolipop) like, when I am creating an intent using action activity(Intent intent = new Intent(context, activity.class)) and then placing it under pending intent(PendingIntent pi = PendingIntent.get activity(context, 0, intent, 0)). Notification not removing from drawer after click, but if there has no action activity mentioned under intent (Intent intent = new Intent()) then it removing.
I have used setautocancel(true) on notification compact builder and also set flag to cancel but did not work. But in one of my other android app same implementation it is working properly without any issue.
Please reply asap, as I need to solve this very quick. Thanks
Thanks for the great tutorial. Everything works perfectly.
BEST!
THANK YOU FROM YOUR TIME…
very well written tutorial,
keep it up bro ..
help us by writing more such tutorials.. 🙂
not working for me. Image is not coming when app is in back
Only working for single device not for other and image not displayed on the notification .What to do for run on all the devices having my installed app.
Hello Trainer, Great Tutorial, Very neat and clean approach.
I have 2 big questions (assuming these are small for you)
(1) Let’s assume, I am using second approach, I mean using Messaging API (ARC), How can I show Title and Message both in Notification Bar (Still we are getting our message as Title content in Notification Bar)… Am I right? OK good, as you have shown in screenshot : https://goo.gl/n2rn1B (due to this, we are seeing incomplete message, because in Notification Bar title has limit maximum 1 line)
(2) Is it not possible for us to show notification’s message in AnotherActivity, whenever we do tap on Notification.
Please try to work on these 2 things, after that your tutorial is the awesome here for everyone… and Guys those want to send message to each and every user using Messaging API, use “/tokens/news” with to and you are done.
Thanks
How to send push notification from advanced rest client new version10.0.6 in android app using firebase?????
Pingback: How to show big images using Firebase Cloud Messaging in Android? - ExceptionsHub
Hii
Can I set the push with a picture that will show automatically on the client notifications?
Right now, I have to pull the message down to show the picture.
Thanks