Firebase message not opening application when clicking on the notification - java

I added the following pice in the manifest to call the onMessageReceived function when a firebase message comes in:
<service android:name=".Notifications"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Here is my onMessageReceive function:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("NotificationService", "Notification received!");
Map<String, String> data = remoteMessage.getData();
String deep_link = data.get("deep_link");
String title = data.get("title");
String body = data.get("body");
Log.d("NotificationService", "Notification received!");
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.context.getApplicationContext(), "1");
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(new MainActivity(), Uri.parse(deep_link));
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(MainActivity.context.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle(title);
builder.setContentText(body);
NotificationManager notificationManager = (NotificationManager) MainActivity.context.getSystemService(MainActivity.context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "1";
NotificationChannel channel = new NotificationChannel(
channelId,
"1",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
But the function is never called does someone know where the problem lays?
I tried to send the notification with and without notification payload, tried the app in background state and foreground state, tried killing the app and then sending the notification
When clicking the notification it doesnt open the app or anything

Related

My Notification Channel is not being created

Whenever I send a notification through fcm.
It says it will use the default from manifest or the android app, I also have mentioned my channel in manifest as default.
It just says that the channel is not created by the app.
Log says
W/FirebaseMessaging: Notification Channel requested (message_notification) has not been created by the app. Manifest configuration, or default, value will be used.
This is my onMessageReceived function.
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+":/ /"+applicationContext.packageName+"/"+R.raw.alert)
Log.d("notofiction Nul", sound.toString())
if(p0.notification!=null){
val title = p0.data["title"]
val message = p0.data["body"]
Log.d("notottg",title+message)
buildNotificationChannel()
if(buildNotificationChannel()){
generateNotification(title!!,message!!)
}
}
else{
val title = p0.data["title"]
val message = p0.data["body"]
Log.d("notottg",title+message)
buildNotificationChannel()
if(buildNotificationChannel()){
generateNotification(title!!,message!!)
}
}
}
This is my createNotificationChannel function
private fun buildNotificationChannel():Boolean {
/*var audioAttributes = AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+"://"+applicationContext.packageName+"/"+R.raw.alert)
Log.d("notisound",sound.toString())*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val CHANNEL_ID = "merchant_notification"
val CHANNEL_NAME = "Merchant Notification"
var notificationChannel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
vibrationPattern=longArrayOf(400, 400, 400, 400, 500, 400, 400, 400, 400)
enableVibration(true)
}
notificationManager= getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
//notificationChannel.setSound(sound,audioAttributes)
}
return true
}
And this is my generateNotification function
fun generateNotification(title: String, message: String) {
val intent = Intent(this#CustomMessagingService, MainActActivity::class.java)
var pendingIntent = PendingIntent.getActivity(this#CustomMessagingService, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
var builder: NotificationCompat.Builder =
NotificationCompat.Builder(this, "merchant_notification")
var audioAttributes = AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+"://"+applicationContext.packageName+"/"+R.raw.alert)
Log.d("notisound",sound.toString())
builder.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.setSound(sound)
notification = builder.build()
Log.d("notot", notification.toString() + " " + sound.toString())
notificationManager.notify(1, notification)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
var nb: Notification.Builder = Notification.Builder(this)
nb.setSmallIcon(R.mipmap.ic_launcher_round)
.setAutoCancel(true)
.setSound(sound, audioAttributes)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.build()
notification = nb.notification
notification.flags = Notification.FLAG_AUTO_CANCEL
notificationManager.notify(0, notification)
}
}
My Manifest Code
<service android:name=".classes.CustomMessagingService"
android:exported="false"
android:enabled="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"
/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="merchant_notification" />
It works for me:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage message) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // channel for notifications
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null) {
List<NotificationChannel> channelList = notificationManager.getNotificationChannels();
for (int i = 0; channelList != null && i < channelList.size(); i++)
notificationManager.deleteNotificationChannel(channelList.get(i).getId());
}
String name = getString(R.string.notification_channel_name);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(getString(R.string.notification_channel_id), name, importance);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
Intent intent;
intent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.notification_channel_id))
.setSmallIcon(R.drawable.logo)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_SOUND)
.setContentTitle(message.getData ().get ("myBody"))
.setContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, builder.build());
}
#Override
public void onNewToken(#NonNull String token) {
}
}
Manifest:
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/notification_channel_id" />

Android unable to receive notification when app is killed using FCM

Android able to receive notification when app is in foreground and background but when I kill it causing unable to receive notification.
I'm not sure what part was wrong.
code in AndroidManifest.xml
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
MyFirebaseMessagingService.java
I don't create MyFirebaseIdService.java for refresh token. I use onNewToken(String mToken) in this class instead.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onNewToken(String mToken) {
super.onNewToken(mToken);
Log.e("NEW_TOKEN",mToken);
}
Here is my onMessageReceived code.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
RemoteMessage.Notification notification = remoteMessage.getNotification();
Map<String, String> data = remoteMessage.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
sendNotification(notification, data);
}
}
sendNotification code, I attempt make it to receive both data payload and notification payload but it still not work.
#RequiresApi(api = Build.VERSION_CODES.O)
private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
String title;
String body;
if (data != null) {
title = data.get("title");
body = data.get("body");
} else {
title = notification.getTitle();
body = notification.getBody();
}
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setLargeIcon(icon)
.setColor(Color.BLUE)
.setSmallIcon(R.mipmap.ic_launcher);
try {
String picture_url = data.get("picture_url");
if (picture_url != null && !"".equals(picture_url)) {
URL url = new URL(picture_url);
Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
notificationBuilder.setStyle(
new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
);
}
} catch (IOException e) {
e.printStackTrace();
}
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.RED, 1000, 300);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
create channel code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT
);
channel.setDescription("channel description");
channel.setShowBadge(true);
channel.canShowBadge();
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.enableVibration(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});
managerCompat.createNotificationChannel(channel);
}
managerCompat.notify(101,notificationBuilder.build());
}
}
You cannot receive notification when killed app for one cause:
Some manufacturers, like HUAWEI, OPPO ecc... make unavailable to push notifications while app is not running, this in order to save your battery life. Of course, important app (WhatsApp, Instagram ecc...) make exception by default. In other hand, there's a way to fix it, every app can get this permission manually via settings->battery (it changes phone by phone).
Now you have to find this permission which affords app to push notifications without running. A tip: when I've tick this one, it doesn't work; I had to unistall app via settings->app, then re-install it again

BroadcastReceiver not being called when pressing Notification Button

Inside the onCreate method of my Service I create a notification by doing the following:
String channelId = "001";
String channelName = "myChannel";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(channel);
Notification notification;
Intent myIntent = new Intent("alarmReceiver");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
Notification.Action action = new Notification.Action.Builder(
Icon.createWithResource(this, R.drawable.ic_stop_black_24dp),
"action string",
pendingIntent).build();
//Modify notification badge
notification = new Notification.Builder(getApplicationContext(), channelId).setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(Notification.CATEGORY_SERVICE)
.addAction(action)
.build();
startForeground(101, notification);
}
The alarmReceiver in the Intent above is registered in my manifest as shown below (I did the following after seeing this question):
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="alarmReceiver" />
</intent-filter>
</receiver>
and here is my AlarmReceiver class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("onReceive - ","was called");
}
}
The notification is shown, as well as the button, but when I press the button nothing happens.
I'm not sure what I'm doing wrong. Any help would greatly be appreciated.
Set PendingIntent to foreground service, And potentially add a flag:
FLAG_UPDATE_CURRENT
PendingIntent pendingIntent = PendingIntent.getForegroundService(this, 0, myIntent, FLAG_UPDATE_CURRENT);
Your broadcast is Implicit, so if you want to use getBroadcast() it may be best to Explicitly declare the receiver by providing the intent with the componentName of the receiver.
eg:
intent.setComponent(new ComponentName("packagename","fully qualified class name"));
Have you declared the service in your manifest?

Push notifications is not working when the application is open?

I'm trying to use FCM and the notifications only works when I'm not using the application .
when I send notification from device A to device B , then device B receive the message and "show the notification pop with the default sound" and every thing is good... (this happens when device B is not using the application).
when I send notification from device A to device B , then device B receive the message in the onMessageReceived() method but "does not show the notification pop with the default sound".. (this happens when device B is using the application, I mean when the application is open and is being used).
this is my code
FireIDService.java
public class FireIDService extends FirebaseInstanceIdService {
private final String TAG = "FireIDService";
#Override
public void onTokenRefresh() {
String tkn = FirebaseInstanceId.getInstance().getToken();
Log.d("Not","Token ["+tkn+"]");
sendRegistrationToServer(tkn);
}
private void sendRegistrationToServer(String token) {
saveDeviceToken(token);
}
private void saveDeviceToken(String deviceToken) {
//some code..
if(response.body().getStatus() == 1){
doStuff();
}
//some code...
}
#Override
public void onFailure(Call<SaveDeviceTokenResponse> call, Throwable t) {
//code...
}
});
}
private void doStuff(){
Intent intent = new Intent(this, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410 /* 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_launcher_background)
.setContentTitle("FCM Message")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1410 /* ID of notification */, notificationBuilder.build());
}
}
FireBaseMsgService.java
public class FireBaseMsgService extends FirebaseMessagingService{
private final String TAG = "FireBaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "test")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background))
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setColor(0xffff7700)
.setVibrate(new long[]{100, 100, 100, 100})
.setPriority(Notification.PRIORITY_MAX)
.setSound(defaultSoundUri);
Intent resultIntent = new Intent(this, SplashActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(SplashActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
notificationBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notificationBuilder.build());
}
}
this is what added to the AndroidManifest.xml file
<service android:name=".FireIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".FireBaseMsgService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
and this is the Notify class to be execute
public class Notify extends AsyncTask<Void,Void,Void>{
private String tkn;
private String title;
private String body;
public Notify(String tkn, String title, String body){
this.tkn = tkn;
this.title = title;
this.body = body;
}
#Override
protected Void doInBackground(Void... voids) {
Log.e("Token: ", tkn);
Log.e("Title: ", title);
Log.e("Body: ", body);
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key=KEY_HERE");
conn.setRequestProperty("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("to", tkn);
JSONObject info = new JSONObject();
info.put("title", title); // Notification title
info.put("body", body); // Notification body
info.put("priority", "high");
info.put("show_in_foreground", "true");
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
}
catch (Exception e)
{
Log.d("Error",""+e);
}
return null;
}
}
If you are using android 8.0+. You need to specify channelId for notification.
When your app is in background (as mention in your first case), the push notification is recieved in system notification tray, rather than your FireBaseMsgService, and it is handled automatically by the system by channelId is genreated by system itself.
When your app is in foreground (second case) your FireBaseMsgService is executed and have to create notification channelId

Firebase push notification activity is not opening when app is in background?

Actually I'm implementing firebasePushNotification service which is working wihtout any issue . Now when I'm receiving push_notification and my app is in foreground by clicking the notification intent is being passed to the desired activity without any error. But when the app is in background or not opened clicking on the notification is not sending the intent to the desired activity and even it's not showing any error . I tried to refer some questions in SO about adding exported=true option in manifest.xml but it couldn't solve my issue.
Code of NotificationManager Class:
public void displayNotification(String title, String body,String post_owner_username,String post_owner_time,
String notif_commenter_username,String notif_comment_time,String follower_username,String type) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx, Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.new_icon)
.setContentTitle(title)
.setContentText(body);
Intent i = new Intent(ctx, ProfileHolder.class);
if (type.equals("likes")) {
Bundle b = new Bundle();
b.putString("post_owner_username", post_owner_username);
b.putString("post_owner_time", post_owner_time);
b.putString("what", "show_notification_post");
i.putExtras(b);
i.putExtra("Open", "starred");
}
else if (type.equals("comments")) {
Bundle b = new Bundle();
b.putString("post_owner_username",post_owner_username);
b.putString("post_owner_time", post_owner_time);
b.putString("notif_commenter_username", notif_commenter_username);
b.putString("notif_comment_time",notif_comment_time);
b.putString("what", "show_notification_post");
i.putExtras(b);
i.putExtra("Open", "starred");
}
else if (type.equals("comment_likes")) {
Bundle b = new Bundle();
b.putString("post_owner_username", post_owner_username);
b.putString("post_owner_time", post_owner_time);
b.putString("notif_commenter_username", notif_commenter_username);
b.putString("notif_comment_time", notif_comment_time);
b.putString("what", "show_notification_post");
i.putExtras(b);
i.putExtra("Open", "starred");
}
else if (type.equals("follow")||type.equals("follow_request")) {
Bundle b = new Bundle();
b.putString("searchUsername", follower_username);
i.putExtras(b);
i.putExtra("Open", "search_profile");
}
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, i, PendingIntent.FLAG_ONE_SHOT);
/*
* Setting the pending intent to notification builder
* */
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotifyMgr =
(NotificationManager) ctx.getSystemService(NOTIFICATION_SERVICE);
if (mNotifyMgr != null) {
mBuilder.setAutoCancel(true);
mNotifyMgr.notify(1, mBuilder.build());
}
}
If you are using firebase push notification
You need to send a click_action attribute ...to open the desired activity when app is in background.
So try ..
Intent i = new Intent(click_action);
click_action is the intent-filter mapping to the desired activity. click_action is mandatory
instead of the Explicit intent call - explicit intent call in the above case will only work when the app is in foreground..
Here is how I've managed to open specific activity from notification when app is in the background/closed and to pass data through Intent.
Application
public class AppConfig extends Application {
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(this);
}
}
Manifest
<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>
<!-- Don't forget to set exported attribute to true -->
<activity android:name=".MainActivity" android:exported="true"/>
MessagingService
public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String body = null;
if(remoteMessage.getNotification() != null) {
body = remoteMessage.getNotification().getBody();
}
String id = null;
// get data that server passed (if it passed any at all)
if(remoteMessage.getData().size() > 0) {
id = remoteMessage.getData().get("id");
}
sendNotification(body, id);
}
private void sendNotification(String messageBody, String id) {
// put data you want to send through intent
Bundle bundle = new Bundle();
bundle.putString("id", id);
// create intent, put data, and
Intent intent = new Intent(this, ActivityLogin.class);
intent.putExtras(bundle);
// IMPORTANT! clearing previous tasks so desired activity will launch
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
// customising the notification
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}

Categories