I am using Firebas mesaging service class. and Its working properly when app is running in foreground but when i clear this application from recent i am not able to access the push notification data for setting it on textview.
I want to store data in database when app is running in background.
I had Used Database to store the value directly but its not working.
public void onMessageReceived(RemoteMessage message) {
database=new SQLiteHelper(getApplicationContext());
database.open();
String image = message.getNotification().getIcon();
String title = message.getNotification().getTitle();
String text = message.getNotification().getBody();
String sound = message.getNotification().getSound();
int id = 0;
database.addQuotes(text,"Xyz");
}
In MainActivity.java in Oncreate method
Bundle extras = getIntent().getExtras();
if (extras != null) {
final String message = extras.getString("message");
quote_text.setText(message);
Toast.makeText(this, "A", Toast.LENGTH_SHORT).show();
}
But message shows null data.
based on this:
I want to store data in database when app is running in background
The service calls which extends FirebaseMessagingService has a method called onMessageReceived which is called when a push notification is received on the front-end (app) add your message to DB there!
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
.....
// parse and add your message to Db here!
Normally when your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
But you can refer this answer on stackoverflow if you want to get notification data-messages in your app while in background.
You may also refer this
Related
The FirebaseMessagingService has the method onMessageReceived() which we should override to handle notifications, but this only works when the app is in Foreground.
To handle notifications even when the app is in background, I used to override the handleIntent, to just call the onMessageReceived().
In FirebaseMessagingService 11.6.0, the method handleIntent became final, with that said, I can't override it as I was doing.
How should I handle notifications when my app is in background in the 11.6.0?
public class NotificationsListenerService extends FirebaseMessagingService {
private static final String TAG = "NotificationsListenerService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
String notifyData = remoteMessage.getData().get("notifData");
if(notifyData.contains("|")){
String[] itens = notifyData.split("\\|");
notifyData = itens[0];
}
String notifyType = remoteMessage.getData().get("notifType");
String title = remoteMessage.getData().get("title");
String message = remoteMessage.getData().get("body");
if(!isAppInForeground(App.getContext())){
sendNotification(title, message, notifyData, notifyType);
}
}
#Override
public final void handleIntent(Intent intent) {
...
this.onMessageReceived(builder.build());
...
}
private void sendNotification(String messageTitle, String messageBody, String notifyData, String notifyType) {
...
}
//Detect if app is in foreground
private boolean isAppInForeground(Context context) {
...
}
}
It's not intended for anyone to override handleIntent(). That's why it was made final. Also, you'll notice that it's completely missing from the javadocs - that's intentional.
If you want to handle a message in any circumstance (both foreground and background), use onMessageReceived(). The javadoc for that method says:
Called when a message is received.
This is also called when a notification message is received while the
app is in the foreground. The notification parameters can be retrieved
with getNotification().
This should work for data messages, but not notification messages sent from the console. Notification messages have different delivery behavior. See the documentation about message types and how to handle them.
I'd add that in FirebaseMessagingService 11.8.0 docs, it is stated in https://firebase.google.com/docs/cloud-messaging/android/receive that if a notification has a data payload it will call onMessageRecieved() when the app is in the foreground, and if the app is in the background the notification and data payload are delivered in the extras of the intent of your launcher Activity.
So, this means you need to decide how to handle the notification in two places, depending on whether the user is actively using the app or if it is in the background.
As you have seen yourself, if you receive the notification while the app is in the foreground, onMessageReceived() is called and you handle the notification there.
When the app is launched from the background, you have 2 options:
1: By default, the notification is sent to your system tray, and when it is clicked it opens your main activity, passing the data (what would have been remoteMessage.getData() in onMessageReceived()) to your activity as intent extras. You can handle the extras in your main activity like so and decide what to do with them, for instance check for a key value and launch a related intent.
// [START handle_data_extras]
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
You can decide what intent to open on-click if you add an intent-filter in your app manifest and a designated "click_action" value in your notification, and then handle the intent extras in the designated activity. See https://stackoverflow.com/a/39665485/3746204
I'd also suggest checking the firebase messaging sample app for ideas: https://github.com/firebase/quickstart-android/tree/master/messaging
i have the same problem after update firebase library version.
i think the easiest way is downgrade firebase library again (i use 11.4.2) and handleIntent() still works !
I have created android application to receive push notification from server but it is not working.
When app is in foreground, it works perfectly. But when we force close app from system tray it does not work.
Below is my json code which I send to FCM.
{"to":"\/topics\/global","data":{"title":"Title","body":"Body"}}
Below is my android function
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("Msg", "Message received ["+remoteMessage+"]");
Map<String, String> data = remoteMessage.getData();
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.addData(data.get("body"));
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("message", data.get("body"));
showNotificationMessage(getApplicationContext(), data.get("title"), data.get("body"), "", resultIntent);
}
Below is code to show notification.
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
I can not find any problem, can any one please help me.
Thank you very much in advance.
Edit :
I have solved my problem by changing phone, in samsung device code is working fine but its problem with MI device itself.
I have also got solution for MI devices, use below steps to enable auto start that application.
Go to settings --> permissions --> autostart. From there, pick the apps you want to receive notifications, and toggle the switch to turn it on.
As per the doc there are two possibilities when notification arrived.
Application is in foreground.
You will get notify in onMessageReceived, and you can get data in this method. You need to generate local notification in system tray.
Handle Notification
You have done this code as mentioned in question.
Application is in background.
You get notification in system tray. You don't need to generate notification here. You will get data in Intent of launcher Activity.
Handle Notification
Here is code of launcher activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent == null || intent.getExtras() == null) {
// your code to handle if there is no notification
} else {
// handle notification
String body = intent.getStringExtra("body");
String title = intent.getStringExtra("title");
//TODO your code to open activity as per notification
}
}
I have done this, and its works for me.
From here,
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
And from this,
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity
You might get complete help from receive message tutorial
when my app in foreground then the notification url link open automatically without user's any contribution.
Now,I want to keep notification in notification bar and when user press the notification that will open the url link.
One more thing I have to mention that,when my app in background it works fine.Notification arrive in notification bar.
I want same thing to do for foreground.
please help,
Thanks in advance.
my FirebaseMessagingServices
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getData().size()>0){
String url = remoteMessage.getData().get("url");
Intent intent = new Intent("com.bellecarib_FCM-MESSAGE");
intent.putExtra("url",url);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
here is my MainActivity code
LocalBroadcastManager.getInstance(this).registerReceiver(mHandler, new IntentFilter("com.bellecarib_FCM-MESSAGE"));
if(getIntent().getExtras() != null){
for(String key: getIntent().getExtras().keySet()){
if(key.equals(("url"))){
mwebView.loadUrl(getIntent().getExtras().getString(key));
Toast.makeText(getApplicationContext(),"Opening The Notification Page",Toast.LENGTH_LONG).show();
}
}
}
The behaviour you are seeing , is when you send notification payload from FCM. If you want a customised behaviour, then send only a data payload and when you receive the message, throw up a notification manually. This means more work for your app (at the cost of customisation). Also data payloads are delivered with a normal priority which means if your device is in idle mode, then FCM Data payload messages are not delivered immediately and deferred till the next maintenance window (Read upon Android Doze mode and App Standby).
Hope this is clear
I am using FCM for Simple notification
When the app is in foreground, everything working properly. I am getting a notification plus the data message inside the onMessageReceived method.
But when app is in background, I am getting notification in system tray. And when I click on the control, it goes to the main activity. And When I parse intent.getExtras();, I am getting only this key data - google.sent_time, from, google.message_id, collapse_key.
How to get the notification message title and Message which is visible in system tray from intent.getExtras()?
I am using FCM console for sending notification I don't have my dedicated server to do this.
Code for receiving the message:
final Bundle extras = intent.getExtras();
final Set<String> keySet = extras.keySet();
final Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()) {
final String key = iterator.next();
final Object o = extras.get(key);
System.out.println(key + ":" + o);
}
As seen in the Handling Messages for Android FCM docs, if the payload you sent has both notification and data, it will be handled separately. The notification part will be handled by the Notification Tray, while the data part will be in the extras of the intent.
AFAIK, there is no way to get the notification payload when the app is in background (always handled by the Notification Tray). However, what you could do is add custom key-value pairs to your data payload instead, like so:
{
"data": {
"notification_title": "title here",
"notification_message": "message here"
}
}
Of course you'll have to make sure that the data value for notification_title and notification_message is the same as to what you set it in the notification payload. Then just retrieve it from the Intent extras like usual.
Firebase Notfication will behave as Data Message when your app is in background or is killed. In these Scenarios, if you want to retrieve your notification Message then you must define it in Key Value pair under
Advanced Option of FCM Console
and then retrieve this message by using this key in your activity which will be open by tabbing the Notification.
if (getIntent().getExtras() != null) {
Object value ;
for (String key : getIntent().getExtras().keySet()) {
if(key.equals("Message Key")) {
value = getIntent().getExtras().get(key); // value will represend your message body... Enjoy It
Log.d("NotificationTag" , key+"____" + value);
}
}
}
Just override the handleIntent() method of FirebaseMessagingService .class it will called in both foreground and background mode and here your can get and parse notification key and payload data
public void handleIntent(Intent intent)
{
String title = bundle.getString("gcm.notification.title");
String body = bundle.getString("gcm.notification.body");
}
Note: it will worked for play service 11
I have successfully implemented the push notification tutorial for Android. Once the notification is received it will immediately perform an action based on the json objects passed via the BroadcastReceiver.
However we would like that the action only be performed once the user clicks the push notification alert in the notification tray. Is this possible? From the tutorials we can choose which activity is opened via the subscribe method.
I am trying to determine when a particular push notification is clicked to launch the app. I am sending the pushes with a custom action and receiving them fine. When the notification is clicked to open the app for the first time, I receive the action and push notification data in the extras. However, once the app is already open / backgrounded, the extras never change. If I open the app from a different push notification OR open the app just from the app icon, the extras remain the same as the original notification that opened the app (or no extras if the app was opened originally just by the icon).
This is my code in onResume() method of my activity
Intent intentNotification = getIntent();
Bundle extras = intentNotification.getExtras();
if (extras!=null) {
String jsonData = extras.getString( "com.parse.Data" );
System.out.println("Message Data : "+jsonData);
}
Any one please help me on this problem..
I also went through the same situation while using Xtify for push notification
I applied a simple logic of creating static variable according to the need. when the specific operation id completed . in my case user registers , then I would make the static variable to empty (public static String MY_GLOBAL_VARIABLE=""). Unless the user doesn't register the variable contains the value
try to implement this logic ...
hope this can help to at least to start.
Try this....
public static String MY_JSON_DATA;
Intent intentNotification = getIntent();
Bundle extras = intentNotification.getExtras();
if (extras!=null) {
MY_JSON_DATA=extras.getString( "com.parse.Data" );
System.out.println("Message Data : "+MY_JSON_DATA);
}
// when open the app , use the value from MY_JSON_DATA and after clear it like MY_JSON_DATA=""
add this method into your Activity which is push notification open
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle extras = intent.getExtras();
setIntent(intent);
if (extras!=null) {
String jsonData = extras.getString( "com.parse.Data" );
System.out.println("New Notification Data : "+jsonData);
String msg;
try {
JSONObject jMsg=new JSONObject(jsonData);
if (jMsg.has("alert")) {
msg=jMsg.getString("alert");
Util.SaveToSharedPref(LoginActivity.this, Constant.ShaPreNotification, Constant.ShaPreNotfMessage, msg);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and onRecevie() method call one custom function which body is same as onNewIntent()
This is important because when app is completely closed i.e it is remove from recent apps /apps history at that time on receive method is called so it getting notification message.
and other time it call onNewIntent() method