Cloud Messaging scheduled sending does not work - java

Hi guys as the title suggests I have a problem regarding Firebase Cloud Messaging, everything works perfectly even when the device does not open the app for a long time, receives notifications perfectly, but the problem occurs when I schedule the daily notification via the console firebase li the first time of sending works and sends the notification to all devices, while the next day at the scheduled time the notification is no longer received and this problem I do not know how to solve it, I have tried everything without any solution, the daily notifications do not are received, can you help me thanks.
#SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class MyFirebaseMessagingService extends FirebaseMessagingService {
/*public static int NOTIFICATION_ID = 1;*/
public static String NOTIFICATION = "notification";
public static String NOTIFICATION_CHANNEL_ID = "com.fourapper.forpaper.channel";
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
generateNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
}
private void generateNotification(String body, String title) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
/*PendingIntent pendingIntent = PendingIntent.getActivities(this, 0 , new Intent[]{intent}, PendingIntent.FLAG_ONE_SHOT);*/
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
/*NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);*/
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_logo_forpapaer)
.setVibrate(new long[]{100, 500})
.setSound(soundUri)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("info")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = null;
if (intent.hasExtra(NOTIFICATION)) {
notification = intent.getParcelableExtra(NOTIFICATION);
}
int notificationId = (int) System.currentTimeMillis();
notificationManager.notify(notificationId, notification);
/*if(NOTIFICATION_ID > 2147483646){
NOTIFICATION_ID = 0;
}*/
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("Channel");
notificationChannel.setBypassDnd(true);
notificationChannel.enableLights(true);
notificationChannel.setVibrationPattern(new long[]{ 0, 500});
notificationChannel.enableVibration(true);
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(notificationId, builder.build());
}
}
below the token
public class GettingDeviceTokenService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
String deviceToken = FirebaseInstanceId.getInstance().getToken();
assert deviceToken != null;
Log.d("Device Token", deviceToken);
}
}
Below are the photos of the firebase cloud messaging console for scheduled daily sending at 12:00 AM Recipient Time Zone
sending setting change screen

Related

Group notification wont show

I am using FCM to send notifications between users when they receive a new message.
I had like to make a group notification from my app so it will show like this:
However, for some reason every new notification that I get, it deletes the other so it always shows only the latest notification.
My code is:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private FirebaseAuth auth;
private FirebaseFirestore db;
private static String GROUP_KEY = "NOTIFICATION";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
createNotificationChannel();
notifyThis(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"),remoteMessage.getData().get("var1"),remoteMessage.getData().get("var2"),remoteMessage.getData().get("var3"));
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "ABC";
String description = "ABCDE";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("191919", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void notifyThis(String title, String message, String var1, String var2, String var3) {
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra("ChatID",var1);
intent.putExtra("ReceiverID",var2);
intent.putExtra("itemID",var3);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "191919")
.setSmallIcon(R.drawable.ic_launcher_custom_background)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, mBuilder.build());
}
}
Is there any reason? Any chance that it is because of the channelId?
Also, I saw that I might need to build multiple notifications however how can I make it dynamic based on the amount of messages that the user gets?
Lets set I get 2 notifications and then I get one more message but I built only 2 notifications, how it will show me the third?
Thank you

Failed to post notification on channel “null”

I have an App which can send notifications to the users but since the new PlayStore Updates needs to match targetSdkVersion 26 the notifications dont work anymore with the error toast Failed to post notification on channel “null”. There are some threads about it but i didnt get the solution. Here is my actual FirebaseMessagingService class:
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_message);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
What do I need to change to make it working again? It would be good if it also works for devices from sdk 24 up.
Since Android Oreo, you need a Channel to send your notifications.
You can do something like this (not tested) :
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_message);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotifyMgr.createNotificationChannel(notificationChannel);
}
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}

Android Version 8.1, Bad notification for startForeground

I have given my couple of days to solve this issue. My app is getting crash whose android version is 8.1. It is working perfectly fine in Android Version 8.0.
I followed the link mentioned below for the solution and tried many solutions given in this link but my application is not opening.
startForeground fail after upgrade to Android 8.1
I check the Android version in FirebaseMessageService class and create the channel for Oreo version but below given error is showing everytime
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:171)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Here below is my code. Please help me to rectify this problem
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
private NotificationManager notifManager;
Context mContext;
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
sendNotification();
}
public void sendNotification()
{
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, m /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logipace")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
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, "LOGIPACE", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(m /* ID of notification */, notificationBuilder.build());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Below is the code which I used in the onCreate() method of my Activity class.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
// Create channel to show notifications.
String channelId = getString(R.string.default_notification_channel_id);
String channelName = getString(R.string.default_notification_channel_name);
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_LOW));
}
Help me to resolve this issue.
Put your logic inside onMessageReceived: Check Firebase quickstart sample.
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle data payload of FCM messages.
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());
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
final String msg = object.getString("msg");
sendNotification(msg);
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.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());
}

Using startForeground with android service

I have found this Question : How to use startForeground? in Stackoverflow and as it says in the command from the top answer the notification constructor and setLastEventInfo is deprecated. I know that's a duplicated post but the other post is 4 years old and has no answer in the commends so I thought i try do ask it again maybe someone can help me with this.
Code:
Notification note = new Notification(R.drawable.ic_launcher,
"Foreground Service notification?", System.currentTimeMillis());
Intent i = new Intent(this, CurrentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Date dateService=new Date(System.currentTimeMillis());
String dateString=dateService.toString().split(" ")[1]+" "+dateService.toString().split(" ")[2]+" "+dateService.toString().split(" ")[3];
note.setLatestEventInfo(this, "Foreground service",
"Now foreground service running: "+dateString, pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;
startForeground(2337, note);
You can use this method. Now with latest API versions you need to set channel for notifications.
private static final String NOTIFICATION_CHANNEL_ID ="notification_channel_id";
private static final String NOTIFICATION_Service_CHANNEL_ID = "service_channel";
.....
private void startInForeground() {
int icon = R.mipmap.icon;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
icon = R.mipmap.icon_transparent;
}
Intent notificationIntent = new Intent(this, CurrentActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.setContentTitle("Service")
.setContentText("Running...");
Notification notification=builder.build();
if(Build.VERSION.SDK_INT>=26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_Service_CHANNEL_ID, "Sync Service", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Service Name");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notification = new Notification.Builder(this,NOTIFICATION_Service_CHANNEL_ID)
.setContentTitle("Service")
.setContentText("Running...")
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.build();
}
startForeground(121, notification);
}

Get multiple GCM messages

This class won't to handle multiple GCM messages and show them on notification bar,currently handle only one, how can make it to handle multiple messages?
public class GCMIntentService extends GcmListenerService {
private static final String TAG = "GCMIntentService";
int notifyid = 0;
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "from:" + from);
Log.d(TAG, "message:" + message);
sendNotification(message);
}
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notifyid, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("New Messsage")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSound)
.setContentIntent(pendingIntent);
int numMessages = 0;
notificationBuilder.setContentText(message).setNumber(++numMessages);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notifyid, notificationBuilder.build());
}
}
}
From the documentation:
public void notify (int id, Notification notification)
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
notifyid never appears to change in the code you've posted, which is why you only see a single notification.

Categories