How to Implement Firebase Push Notification in Your Android App?

0
Shares
How to Implement Firebase Push Notification in Your Android App?
5 (100%) 4 votes

Firebase Push Notification Android Tutorial

During Google I/O 2016 conference, Google announced major improvements to their Firebase product with a lot of features for mobile application developers.

In case if you don’t know about Firebase, then here’s a brief idea about it: Firebase is a Cloud Service Provider, provided by Google, which provides Mobile Backend as a Service (MBaas).

Firebase gives you tool and infrastructure you need to build better mobile app and grow business successfully. It provides its features divided into three groups mainly: Develop, Grow, and Earn.

firebase notifications

What’s even more interesting is the fact that all of these features provided by Firebase will be connected to Analytics. And it doesn’t matter which feature you use, you’ll get Analytics for free.

There are 15 new features in total among which only 4 features are paid. You can check them out from here.

With Firebase, you can quickly sync up your data and make it available on your app.

In simple words, FCM is a cross platform messaging solution which allows users to reliably send and deliver messages at free of cost.

Now, as you probably know that in order to continuously engage your users and keep content fresh, it is important to retain them. And it has now become easier with Firebase Cloud Messaging by sending push notification to all your Android app users anywhere in the world.

In today’s Android tutorial, you’ll learn how to implement Firebase push notification in your Android app.

Let’s Get Started!

Create a new project under the file menu and click on Next.

Screenshot_1
Now select your form factor and click Next.

Screenshot_2

In the next tab, Select Empty Activity and proceed further.

Screenshot_3

In the last tab, write your project Activity name and click Finish.

Screenshot_4

Now open the Firebase tools in Android Studio 2.2 Tools -> Firebase

Screenshot_6

Now setup the Firebase cloud notification by following the steps.

Screenshot_7

Click on the Connect to Firebase button shown in the right panel.

Screenshot_8

Name your Firebase Project and click on Connect to Firebase.

Screenshot_9

Next, Add FCM to App module (click on “Add FCm to your app”)

Screenshot_10

Screenshot_11

After adding the FCM, Extend FirebaseInstanceIdService.

Add new class and add snippet in Manifest.

Screenshot_12

//Register Service in manifest for Token Refresh

<service
android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>

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.
*/
//
@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);
}
/**
* 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.
}
}

Now Extend FirebaseMessagingService.

Add new Class and add a snippet in Manifest.

Screenshot_12

//Register Service in manifest to Receive Message

<service
android:name=".fcm.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>

public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

// TODO(developer): Handle FCM messages here.
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());
sendNotification("text");
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}


/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
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());
}
}

Check your project and Access Push notification.

Screenshot_14

Screenshot_15

Screenshot_16
Start Integration in Code

A) MainActivity.Java

//Retrive Data from Firebase Notification

public class MainActivity extends AppCompatActivity {
private TextView tvNotificationDetails;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
setNotificationData(getIntent().getExtras());
}
private void initControls() {
tvNotificationDetails = (TextView) findViewById(R.id.tvNotificationDetails);
}
private void setNotificationData(Bundle extras) {
if (extras == null)
return;
StringBuilder text = new StringBuilder("");
text.append("Message Details:");
text.append("\n");
text.append("\n");
if (extras.containsKey("title")) {
text.append("Title: ");
text.append(extras.get("title"));
}
text.append("\n");
if (extras.containsKey("message")) {
text.append("Message: ");
text.append(extras.get("message"));
}
tvNotificationDetails.setText(text);
}
}

B) activity_main.xml

//Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
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="com.firebase.pushnotification.MainActivity">
<TextView
android:id="@+id/tvNotificationDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Here notification details will be display" />
</RelativeLayout>

Once you complete the code. Run the demo. You’ll see a screen like below:

device-2016-10-13-150939

Now, open your Firebase Console and send a push notification. You’ll receive it in the notification bar like below:

device-2016-10-13-150925

Now click on the notification to open it in your demo Firebase project. You’ll have a screen like below:

device-2016-10-13-150648

Bingo!

This is how you can easily implement app push notifications. If you face any difficulty implementing it in your native Android app, then you can contact our app developers.

You can use the notifications console to compose and send notifications to all supported targets according to your requirements regarding push notification services.

In case you’re not a technical person and wish to add this feature in your Startup app, you can hire Android app developer from us as we’re a leading Android app development company in India. Throughout our 5 years journey, we’ve helped 25+ successful startups to build their mobile apps and build 2000+ mobile applications overall. You can also check our portfolio.

In case, if you still have any query or confusion regarding push notification app development, then you can get in touch with us through contact us form. The consulation is absolutely free of cost. You can grab a free copy of this Firebase demo from Github as well.

This page was last edited on August 4th, 2018, at 0:39.
 
0
Shares
 

Have an App Idea?

Get your free consultation now