Google firebase push notification android

Aneh Thakur
TrinityTuts
Published in
3 min readMar 26, 2020

If you want to send a notification to the android application you can use firebase push notification. Implementation of firebase takes less than 3 minutes you need to login to https://console.firebase.google.com/ using your google account.

Create a new project on click on create a project and fill the required information.

Now once you redirected to dashboard click on the android icon to add your project in the console.

Once, you add your project in the next step you need to download google-services.json file which we add in our android project.

Now open your existing android project or create a new project.

Add the required library in your build.gradle files. Open project build.gradle file and add this dependency

classpath ‘com.google.gms:google-services:4.3.2’

Now open your app build.gradle file and add dependency as shown in the below code.

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

implementation 'com.google.firebase:firebase-messaging:17.4.0'
implementation 'com.google.firebase:firebase-core:16.0.1'
}

apply plugin: 'com.google.gms.google-services'

Now syn your project to load all dependencies.

Edit your MainActivity.java file and add below code to generate FCM id

FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}

// Get new Instance ID token
String token = task.getResult().getToken();

// Log and toast
String msg = token;
Log.d(TAG, msg);
}
});

After the above code, you can open your AndroidManifest.xml file and add internet permission

<uses-permission android:name="android.permission.INTERNET" />

And also we need to create a service file that Handel notification which we send from Firebase so create new service class MyFirebaseMessagingService.java and add below code in that file

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFcmListenerService";
private NotificationManager notifManager;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);

// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
Log.e(TAG, "From: " + remoteMessage.getFrom());
//createNotification("Hiii", this);
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("data"), this);
}

// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(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, Context context) {
Log.e("rsp", messageBody);

String title = "Notification";
String desciption = messageBody;

Intent intent = null;

try {
JSONObject message = new JSONObject(messageBody);
title = message.getString("title");
desciption = message.getString("msg");
intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
} catch (JSONException e) {
e.printStackTrace();
}

NotificationCompat.Builder builder = null;
final int NOTIFY_ID = 0; // ID of notification
String id = "mychannel"; // default_channel_id

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

if (notifManager == null) {
notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}

builder = new NotificationCompat.Builder(context, id)
.setContentTitle(title)
.setContentText(desciption)
.setContentIntent(pendingIntent)
.setSound(defaultSoundUri)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
} else {
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
builder.setContentTitle(title)
.setContentText(desciption) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker("Accept your request")
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}

Notification notification = builder.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFY_ID, notification);
}

}

And also call this service inside AndroidManifest.xml file

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

If you want to learn how to send notification from Server or from Firebase console please follow this post Firebase push notification

Source: https://trinitytuts.com/firebase-push-notification-android/

--

--