Push notification is not showing on notification bar - android

I have implemented the firebase push notification by following a YouTube video and its working fine when app is in the background but when the app goes on the foreground it will not show the notification but I can see the notification coming in the logcat.
here is the code-
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
getFirebaseMessage(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
public void getFirebaseMessage(String title, String msg){
Log.d("abc", title);
Log.d("abc", msg);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "plasmatechannel")
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle(title)
.setContentText(msg)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(101 , builder.build());
}
}

Starting from API level 26, all notifications must be assigned to a channel to set the behavior that is applied to all notifications in that channel.
Please try to implement the below way in your existing code
NotificationCompat.Builder notificationBuilder = null;
try {
if (Build.VERSION.SDK_INT >= 26) {
try{
NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.deleteNotificationChannel(Constant.CHANNEL_ID);
NotificationChannel channelnews = new NotificationChannel(Constant.CHANNEL_ID, "Breaking News", NotificationManager.IMPORTANCE_HIGH);
channelnews.enableLights(true);
channelnews.setShowBadge(false);
channelnews.enableVibration(true);
channelnews.setLightColor(Color.WHITE);
channelnews.setVibrationPattern(new long[]{100, 200, 100, 200, 100, 200, 100});
channelnews.setSound(url,new AudioAttributes.Builder().build());
notificationBuilder = new NotificationCompat.Builder(this, Constant.CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher);
notificationManager.createNotificationChannel(channelnews);
}catch (Exception e){
e.printStackTrace();
}
} else {
notificationBuilder = new NotificationCompat.Builder(ctx,"")
.setSmallIcon(R.mipmap.ic_launcher);
}
} catch (Exception e) {
e.printStackTrace();
}
if (notificationBuilder == null) {
notificationBuilder = new NotificationCompat.Builder(ctx,"")
.setSmallIcon(R.mipmap.ic_launcher);
}
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(message);
notificationBuilder.setSubText(subtext);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationNumber, notificationBuilder.build());
Please read detail from
https://developer.android.com/training/notify-user/channels
https://developer.android.com/reference/android/app/NotificationChannel
hope it may help you

That's how the Firebase Push Notification works. It will show notification when your app is in the background. When it is in the foreground, only onMessageReceive is called and you have to perform some action (maybe changing the UI) to notify the user because they are using your app.

Related

Unable to received notification in device notification section in android

This is my code to receive notification
public class FirebaseMessageReceiver
extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageTitle,String messageBody) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {500,500,500,500,500};
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
i am trying to received notification from firebase console i am able to get to get call back when fire notification i am also getting title and msg code executed successfully but i am unable to see notification in notification section of device can any one please help me what i am doing mistake .
Do you use notification channel?
If you are using Adroid 8 or higher it's expected behavior:
Starting in Android 8.0 (API level 26), all notifications must be
assigned to a channel or it will not appear.
https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels
Here you can find detail tutorial how to create notification channel:
https://developer.android.com/training/notify-user/channels
For devices running Android O or higher, you need to create a notification channel first in order to receive notifications like this:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel.setDescription("This is Channel 1");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
Also, you need to pass this CHANNEL_ID constant in NotificationCompact.Builder constructor like this:
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this, CHANNEL_ID)

BigPictureStyle Notification not working in AndroidX

Code:
here is the code to popup notification on button click
notificationbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "noti", Toast.LENGTH_SHORT).show();
Intent i=new Intent(getActivity(),OrderTrack.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(),(int) Calendar.getInstance().getTimeInMillis(),i,0);
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.half_bicycle);
Notification builder=new NotificationCompat.Builder(getActivity(),"1")
.setSmallIcon(R.drawable.half_bicycle)
.setContentTitle("title")
.setContentText("Text")
.setLargeIcon(bitmap)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(bitmap)
.bigLargeIcon(null))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.build();
Notification notif = new Notification.Builder(getContext())
.setContentTitle("New photo from ")
.setContentText("subject")
.setSmallIcon(R.drawable.half_bicycle)
.setLargeIcon(bitmap)
.setStyle(new Notification.BigPictureStyle()
.bigPicture(bitmap))
.build();
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
notificationManager.notify(101, notif);
});
Here I am trying to use BigPictureSt
yle notification. I hava tried two variation of code. But both doesn't give any result/notification.
All the above code is inside a fragment.Is this a reason why it's not working?
I have set the App style to NoActionBar.Is this a reason why it's not working?
Please answer this questions with a proper solution !!!!
Adding the Following code doesn't solve the problem
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
notificationManager.notify(101, notif);
The code is fine and there is nothing wrong with it but most importantly you forgot to show the notification itself i.e you are not using the objects that are created.
So show the notification like this...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
notificationManager.notify(101, notif);//101 is notification id
EDIT:
If you are targetting Android Oreo and above you need to create the channels for notification like this. Use this function to create notification channel and set this channel id on a notification while creating it...
String channelId = "some_channel_id";
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
Complete code:
notificationbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createNotificationChannel(); //Create notification channel
Toast.makeText(getContext(), "noti", Toast.LENGTH_SHORT).show();
Intent i=new Intent(getActivity(),OrderTrack.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(),(int) Calendar.getInstance().getTimeInMillis(),i,0);
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.half_bicycle);
Notification builder=new NotificationCompat.Builder(getActivity(),"1")
.setSmallIcon(R.drawable.half_bicycle)
.setContentTitle("title")
.setContentText("Text")
.setLargeIcon(bitmap)
.setChannelId(CHANNEL_ID) // Channel Id
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(bitmap)
.bigLargeIcon(null))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.build();
Notification notif = new Notification.Builder(getContext())
.setContentTitle("New photo from ")
.setContentText("subject")
.setSmallIcon(R.drawable.half_bicycle)
.setLargeIcon(bitmap)
.setChannelId(CHANNEL_ID) // Channel Id
.setStyle(new Notification.BigPictureStyle()
.bigPicture(bitmap))
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getActivity());
notificationManager.notify(101, notif);//101 is notification id
}
});
For more info visit this : https://developer.android.com/training/notify-user/channels

Notification not showing in samsung oreo devices

I encountered a strange problem today, push notification is not showing in samsung devices which have oreo in it but it's working fine in other oreo devices. Here is the code i am using:
private void sendNotification(String messageTitle,String messageBody) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder=null;
try {
Intent intent = new Intent(this, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String NOTIFICATION_CHANNEL="NB Shop Notification";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
.setSound(defaultSoundUri)
.setChannelId(NOTIFICATION_CHANNEL)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/* Create or update. */
NotificationChannel channel;
channel=new NotificationChannel(NOTIFICATION_CHANNEL,
NOTIFICATION_CHANNEL,
NotificationManager.IMPORTANCE_DEFAULT);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build());
}catch (Exception e)
{
Log.d("sendNotification",e.toString());
}
}
It does not showing any error in log.
I found the issue which causing the problem, the constructor(NotificationCompat.Builder(this)) of NotificationCompat.Builder which has only single parameter is deprecated,
To get rid of deprecation we have to send channel id with constructor, So i have changed my code and passed channel id to the constructor like this:
NotificationCompat.Builder(this,NOTIFICATION_CHANNEL)
also removed
.setChannelId(NOTIFICATION_CHANNEL)
and now this code is also working on samsung devices.

Oreo Notification Bar Round Icon

I want to know that how can I change the notification bar small icon in android Oreo (API 26). It has round white icon showing in the notification bar. How can I change it? Manifest file default notification icon set as below.
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_status" />
See the image below
There is a bug in Firebase SDK 11.8.0 on Android 8.0 (API 26), which causes the display of a white version of the app's launcher icon in the status bar instead of the notification icon.
Some people have fixed it by overriding the Application class's getResources() method.
Another way that worked for me was to use an HTTP POST request to send the notification as a data message:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/test",
"data": {
"title": "Update",
"body": "New feature available"
}
}
And then subclass FirebaseMessagingService to display the notification programmatically:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent i = new Intent(context, HomeActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, i,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this, GENERAL_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_chameleon)
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("body"))
.setContentIntent(pi);
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
In the end, I got this, even on Android 8.0:
Remove <meta-data> tag from AndroidManifest.xml.
Notification Builder has .setSmallIcon(int icon, int level) which accepts icon as a compulsory argument & level parameter as an optional argument.
NOTE: .setSmallIcon accepts drawables & DOES NOT accept mipmaps.
This is how it should be according to Android 8.0 Oreo Notification Channels & behaviour changes:
public class MainActivity extends AppCompatActivity {
private CharSequence name;
private int notifyId;
private int importance;
private String id;
private String description;
private Notification mNotification;
private NotificationManager mNotificationManager;
private NotificationChannel mChannel;
private PendingIntent mPendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.btnNotification.setOnClickListener(v -> notification());
}
private void notification() {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyId = 1;
description = "Hello World, welcome to Android Oreo!";
Intent intent = new Intent(this, MainActivity.class);
mPendingIntent = PendingIntent.getActivity(this, notifyId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (SDK_INT >= O) {
id = "id";
name = "a";
importance = NotificationManager.IMPORTANCE_HIGH;
mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.WHITE);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[] {100, 300, 200, 300});
mNotificationManager.createNotificationChannel(mChannel);
mNotification = new Notification.Builder(MainActivity.this, id)
.setContentTitle(id)
.setContentText(description)
.setContentIntent(mPendingIntent)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build();
} else {
mNotification = new Notification.Builder(MainActivity.this)
.setContentTitle(id)
.setContentText(description)
.setContentIntent(mPendingIntent)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setLights(Color.WHITE, Color.RED, Color.GREEN)
.setVibrate(new long[] {100, 300, 200, 300})
.build();
}
mNotificationManager.notify(notifyId, mNotification);
}
}

Android Wear: Timer like notification card on wear device

I'm working on implementation of Pomodoro app for Android Wear.
I want to make similar to standard timer UI/UX, I guess it's implemented using displaying/updating notification with timer as title, so I'm showing notification and updating it periodically from Service:
private void updateNotification() {
Intent stopActionIntent = new Intent(this, PomodoroActivity.class);
stopActionIntent.setAction(PomodoroActivity.ACTION_STOP);
PendingIntent stopActionPendingIntent = PendingIntent.getActivity(this, 0, stopActionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action stopAction = new NotificationCompat.Action.Builder(
R.drawable.ic_stop,
getString(R.string.stop_pomodoro),
stopActionPendingIntent)
.build();
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bg_pomodoro_timer))
.setContentTitle(convertDiffToTimer(System.currentTimeMillis(), timerDeadlineMs))
.setPriority(Notification.PRIORITY_MAX)
.setOngoing(true)
.extend(new NotificationCompat.WearableExtender().addAction(stopAction))
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, notification);
}
Unpleasure problem with such solution is blinking of notificaiton.
Any ideas how escape blinking? Or maybe other way to achieve target behaviour?
To update ongoing/existing notification -
Use Same Id of Notification in Builder
Use .setOnlyAlertOnce(true)
NotificationCompat.Builder notificationBuilder;
public void generateNotificationForTimer(String timeInString, boolean isFirstTime) {
if (isFirstTime) {
notificationBuilder = new NotificationCompat.Builder(this)
.setStyle(new NotificationCompat.BigPictureStyle())
.setOnlyAlertOnce(true)
.setContentTitle("Timer Notification Demo")
.setContentText("Time - " + timeInString)
.setSmallIcon(R.drawable.common_signin_btn_icon_dark);
NotificationManagerCompat.from(this).notify(110, notificationBuilder.build());
} else {
notificationBuilder.setContentText(timeInString);
NotificationManagerCompat.from(this).notify(110, notificationBuilder.build());
}
}

Categories

Resources