This question already has answers here:
FCM Schedule delivery date or time of push notification
(2 answers)
Closed 6 years ago.
I am trying to schedule particular time and want to send notification using Firebase. I am working on the project where I have to send the notification before the match start. Currently my notification is working on real time but I can't found any way to schedule it for the specific time.
For the real time I am using this particular code.
//Class extending service as it is a service that will run in background
public class NotificationFirebaseListener extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
String test;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody() + "=====>");
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Message data payload: " + remoteMessage.getData());
test = String.valueOf(remoteMessage.getData());
}
sendNotification(test);
}
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, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Bus Tracking")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
The best way to achieve this is use the Firebase Notification composer to schedule your notifications for your app: https://firebase.google.com/docs/notifications/.
If you want another way to achieve these via code, I suggest you to schedule your notification using a ScheduledThreadPool. You can read more about this in the oracle documentation: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html.
Related
Firebase offers two ways to seding a push notifications, using it's firebase console and using a server like in GCM was did before. Now we are translating our servers from GCM to Firebase, and we need to receive and show FCM notifications in the app.
I have the implementation of the official firebase website done, with the sample codes done, but I'm stuck on this part. When our server sends the push notification to Firebase, and firebase send's to my app, I'm receiving the notification in onMessageReceived method with a RemoteMessage parameter. I know that the message is inside RemoteMessage parameter, but I can't find any guide or sample code in the Firebase official documentation about how to deal with this to show the notification text on the android device notification bar.
As you can see on the official guides, it is not explained how to extract the message without problems from the RemoteMessage parameter. I know that you can search inside and find the String but I want to find a official guide about how to correctly and safely deal with this.
In the official documentation you have only this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
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());
// Handle message within 10 seconds
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
And this (which is not being called on the guide):
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);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_main)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
I have done something like this I am using addNotifcation() in place of sendNotification()
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getData().get("body"));
addNotification(remoteMessage.getData().get("body"), remoteMessage.getData().get("Nick"));
}
private void addNotification(String message, String title) {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher1)
.setContentTitle(title)
.setContentText(message);
Intent notificationIntent = new Intent(this, app.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
You will recieve a json onMessageRecieve from server then you need to parse that json and get values out of it.Once you have parsed value you can send it with sendNotification() Method and show what you require
Check below method, its working fine, I am getting json data from server in notification.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
AppLog.Log(TAG, "From: " + remoteMessage.getFrom());
JSONObject json = null;
if (remoteMessage.getData().size() > 0) {
Log.v(TAG, "Message data " + remoteMessage.getData());
json = new JSONObject(remoteMessage.getData());
AppLog.Log(TAG, "Json object " + json);
}
if (json != null) {
try {
int icon = R.mipmap.ic_launcher;
int mNotificationId = 001;
// MainDrawerActivity is the class which open on the click of notification in status bar
Intent intent = new Intent(this, MainDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//FLAG_UPDATE_CURRENT is important
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this);
Notification notification = mBuilder.setSmallIcon(icon).setTicker("your title").setWhen(0)
.setAutoCancel(true)
.setContentTitle("your title")
.setStyle(new NotificationCompat.BigTextStyle().bigText("message"))
.setContentIntent(pendingIntent)
.setContentText("message").build();
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hey all i got a tough problem and need advice. I have constructed a notification manually after recieving a FCM data payload. This is how the notification gets created both in foreground and background since its a data payload:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
String msg = remoteMessage.getData().get("message");
sendNotification(msg);
}
private PendingIntent createIntent(String msg) {
Intent intent = new Intent(this, SportsActivity.class);
Bundle b = new Bundle();
b.putString(Constants.KEY_GO_TO_TAB, Constants.KEY_DASHBOARD_HOCKEY_SCORE_TAB);
intent.putExtras(b);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
return pendingIntent;
}
private void sendNotification( String messageBody) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
android.support.v4.app.NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody))
.setContentText(messageBody)
.setColor(ContextCompat.getColor(this, R.color.hockey_brand))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(createIntent(messageBody));
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
it seems to function fine. The issue im having is i want the notification to NOT SHOW in when the app is in the foreground. is there not a way to do this without scanning the activity task ? as this requires a permission
i've read this article but this how to know you've went from foreground to background. also android.permission.GET_TASKS is deprecated and REAL_GET_TASKS permission is not for third party either. I simply want to know at any given time that the user is either in foreground or background so i know if i should show a notification or not. I wonder if firebase itself has something. When you send a "Notification payload" from the firebase console if the app is not in the foreground is does not show in the notification panel so there should be a way to do this.
Alternatively you can choose not to show your notification when your app is in foreground by implementing Application.ActivityLifecycleCallbacks
in your Application.
Then you can check if your app is in foreground or background.
Source
This question already has answers here:
Firebase onMessageReceived not called when app in background
(30 answers)
Closed 6 years ago.
In Firebase onMessageReceived(RemoteMessage remoteMessage), this method will be called when your app is in Foreground. So, on clicking the notification you can open a different Activity, say NotiicationActivity.
But what if your app is in background, then this method will not be called, and on clicking the notification only a Launcher Activity will be opened.
So how to open the NotificationActivity on clicking the notification even if our app is in background.
My Code is this :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("key", messageBody);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap icon2 = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Sample")
.setContentText(messageBody)
.setAutoCancel(true)
.setLargeIcon(icon2)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(new Random().nextInt() /* ID of notification */, notificationBuilder.build());
}
}
onMessageReceived is only triggered when the application is in foreground.
If the app is backgrounded, you may still be able to receive the notification but onMessageReceived will not be triggered.
So my suggestion,
on the receiving activity, you can still get the data from the notification by using:
getIntent().getExtras();
This should work accordingly. Hope this helps :)
try and follow below link :
Firebase Cloud Messaging for Android
In your sendNotification() method :
private void showNotification(String message){
Intent intent=new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("key", messageBody);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("FCM Sample")
.setContentText(message)
.setLargeIcon(icon2)
.setContentIntent(pendingIntent);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
AT this moment I achive to get Push Notifications (Firebase) to my client.
I followed the instructions onf firebase.
Now, as the app is a message client, I'm receiving a lot of pushes (meanwhile the app is ni background and foreground).
What I tried (and found here: https://developer.android.com/training/wearables/notifications/stacks.html)
So my code, right now is:
public class FCMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Logger.d("Notification Body:" + remoteMessage.getNotification().getBody()
+ "\n DATA:" + remoteMessage.getData().toString());
String jid = remoteMessage.getData().get("jid");
sendNotification(remoteMessage.getNotification().getBody(), jid);
}
private void sendNotification(String messageBody, String jid) {
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);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher_chv)
.setContentTitle(getString(R.string.notification_title))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setGroup(jid);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
AS you can see, I receive in data bundle, the parameter "jid", that identifies the user who send the message. So I use it to try to stak all theis messages, and at the end , have 1 (stacked)notification(s) for every jid.
But, the notifications don't stack when the app is in Background, even more..it launches the notications that where stacked before.
IS there any work around to solve it?
Log of what I receive from notification push:
23304-17215 D/ChatListRealmAdapter: ║ Notification Body:Ana ha enviado un mensaje
23304-17215 D/ChatListRealmAdapter: ║ DATA:{'jid':'ana1234#domain.com'}
I have implemented push by firebase.
I'm sending notifications but I am getting status of "Failed". When I send notification to all devices it is marking as completed but I am still not getting messages in device.
Even when I send messages to single devices it will also show failed and will not receive notification on device.
The code is
private static final String TAG = "StartingAndroid";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//It is optional
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
//This method is only generating push notification
private void sendNotification(String title, String messageBody) {
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);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
Your sender ID mismatched or you have entered incorrect project ID in your Application.
Looking at logs, I think you are sending to specific devices via registration id but we see an error with mismatched sender id.Please check that these registration ids are valid and apply to the correct app.