Android| Java Notifications not appearing in API 25 and lower - android

I have a firebase push notifications that sends text messages. My notifications appear in API 26 onward, but on APIs lower, (currently testing with API 22) and the messages are successfully sent, but they dont appear on the (API 22) device. What could be the problem?
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
createNotificationChannel();
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String dataMessage = remoteMessage.getData().get("message");
String dataFrom = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setPriority(NotificationCompat.PRIORITY_HIGH);
Intent intent = new Intent(click_action);
intent.putExtra("message", dataMessage);
intent.putExtra("from_user_id", dataFrom);
PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, builder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Personal Notifications";
String desc = "Include all the personal notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(getString(R.string.default_notification_channel_id), name, importance);
notificationChannel.setDescription(desc);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
What could be the problem?

If you have situation, when notification appears in status bar, but a floating window not popping up, you should add in your NotificationCompat.Builder
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
because such notifications are called a heads-up notifications and it should have high priority and use ringtones or vibrations on devices running Android 7.1 (API level 25) and lower

The issue is you have targeted Oreo and above in your createNotificationsChannel.
Exact place you target oreo and above is:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
The reason why this has happened will be because of the code listed below since it was added in API level 26. You will need to find an alternative version for lower levels.
notificationManager.createNotificationChannel(notificationChannel);

I had this a while ago. Keep your createNotificationChannel() method in your main class. However, I suggest creating a different class with a static method (to create your notification) then just call it in the FirebaseMessagingService class. Try this:
public class NotificationHelper {
public static void displayNotification(Context context,String title,String body){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,CHANNELID)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(1,mBuilder.build());
}
}
Then in your FMService class, just call the static method after your notification channel like so:
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
createNotificationChannel();
if(remoteMessage.getNotification()!=null){
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
NotificationHelper.displayNotification(getApplicationContext(),messageTitle,messageBody);
}
You should be fine.

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)

Notification in Samsung and Xiaomi show This app hasn't send you any notification

I have a problem with notifications where the notification doesn't appear on my xiaomi and samsung devices but works for the other device. I've tried what people recommend like trying auto start, managing battery settings, but it still doesn't appear on both devices. I also tried to use the notify library but the results were the same. Strangely, when I checked the notification setting and then clicked on the application, it appeared as shown below
samsung
This is my notification code :
public void showNotification() {
String appname = "App Name";
String title = "Notification Title";
String text = "This is the notification text";
String iconUrl = "http://url.to.image.com/image.png";
NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
TaskStackBuilder stackBuilder = TaskStackBuilder.from(MainActivity.this);
stackBuilder.addParentStack(NewsActivity.class);
stackBuilder.addNextIntent(new Intent(MainActivity.this, NewsActivity.class));
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setContentTitle(title).setContentInfo(appname).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo_wanda_flp)).setContentText(text).setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.logo_wanda_flp);
notifyManager.notify("textid", 123, builder.getNotification());
}
The code won't work on Android 8 (API 26) and above without first registering a notification channel. On Android before that, it will work just fine.
Some of the code snippets below are taken from here.
Creating a notification channel
Register notification channels inside your activity before attempting to show any notification. Alternatively, you can register them inside a custom Application class before any activities or services start (but this won't be shown here for the sake of simplicity).
#Override
public void onCreate(Bundle savedInstanceState) {
createNotificationChannel(); // Registering a notification channel
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
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);
}
}
Deliver the notification
public void showNotification() {
// ...
// NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
// Replace with line below.
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID);
// ...
}

Cannot resolve Method "builder()"

I want to send notifications to topics with FCM without using the Firebase console. When I build a new message with the help of Firebase Documentation it´s a problem.
Picture of the problem
Here my Codes:
public void sendToTopic() {
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic("1")
.build();
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
public void onMessageReceived(RemoteMessage remoteMessage) {
}
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);
String channelId = ("asda");
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.book_icon)
.setContentTitle("Test")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
The Message class is inside the Firebase admin sdk but you cannot use that in your android project, you can only use firebase admin sdk in the server side and there you will be able to use the Message class. Check the docs for reference:-
https://firebase.google.com/docs/cloud-messaging/manage-topics

Notification not received in android API eval 26 [duplicate]

This question already has answers here:
Notification not showing in Oreo
(24 answers)
Closed 4 years ago.
I try to receive notification in android Oreo. But App does not receive any
notification. I also create notification Chanel but it's not work
If I send a notification from fcm then app received. but using the token app not received any notification. In other lower, version notification work proper. In Oreo it does not work.
Here is my MyFirebaseMessagingService class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
public static final String NOTIF_CHANNEL_ID = "my_channel_01";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getData());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotifChannel(this);
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void createNotifChannel(MyFirebaseMessagingService
myFirebaseMessagingService)
{
NotificationChannel channel = new NotificationChannel(NOTIF_CHANNEL_ID,
"MyApp events", NotificationManager.IMPORTANCE_LOW);
// Configure the notification channel
channel.setDescription("MyApp event controls");
channel.setShowBadge(false);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = getApplicationContext().
getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
Log.d(TAG, "createNotifChannel: created=" + NOTIF_CHANNEL_ID);
}
private void sendNotification(Map<String, String> data) {
int num = ++NOTIFICATION_ID;
Bundle msg = new Bundle();
for (String key : data.keySet()) {
Log.e(key, data.get(key));
msg.putString(key, data.get(key));
}
Intent intent = new Intent(this, HomeActivity.class);
if (msg.containsKey("action")) {
intent.putExtra("action", msg.getString("action"));
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, num /*
Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(instauser.application.apps.R.drawable.icon)
.setContentTitle(msg.getString("title"))
.setContentText(msg.getString("msg"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(num, notificationBuilder.build());
}
}
I also create a notification channel but it's not work
You created notification channel, but didn't set it to notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
...
.setChannelId(NOTIF_CHANNEL_ID)

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);
}
}

Categories

Resources