Send Notification Update when firebase database is updated - android

I am new to android Firebase and I want that when any new value is added to Firebase then I get any notification like your database is updated or so.. How can I do that..
Please help

You can do this by using Push Notification , During Registration, get the generated token and save it your database along with user details .
whenever a key/child is updated
fire up the Event to that tokenID
you should have a broadcast Receiver in you application which monitors the incoming firebase message
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
here is an Example https://github.com/firebase/friendlychat/blob/master/android/app/src/main/java/com/google/firebase/codelab/friendlychat/MyFirebaseMessagingService.java

Related

FCM: Can We Send the 2 Types of Notifications and to Open Different Activities in Android App

I am implementing FCM notifications using cloud functions. In a single app I want to send 2 notifications and whenever the notification is received then the app should open with a different activity.
Suppose A is a sender who sends the notification to B(where B is the receiver).
Here it successfully sends the notification and whenever the user clicks on the notification it goes to desired Intent
Now, Whenever B needs to send the notification to A
*I am receiving the notification in an app but when I click on the notification it is going to the above notification Intent page.But I need to redirect to other Intent with data *
Any suggestions in this regard will be appreciated.
Yes, you should use
"android":{
"notification"{
"click_action":"OPEN_ACTIVITY_1"
}
}
and then in android app
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
If you have problem with receiving notification in app you should log every push output:
public class FcmListenerService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.i(TAG, "Message received");
// Not getting messages here? See why this may be: https://firebase.google.com/support/faq/#fcm-android-background
Log.i(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.i(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.i(TAG, "Message notification: " + remoteMessage.getNotification());
}
}
}
It will only works if app is in foreground. When your app is in the background, notification messages are displayed in the system tray, and onMessageReceived is not called - https://firebase.google.com/support/faq/#fcm-android-background

What is the Android equivalent of iOS's didReceiveRemoteNotification?

The full method signature is...
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void)
What I want to be able to do is have the device respond when a push notification arrives. For example, the app might automatically navigate to a particular screen to show some data that's identified in the notification.
Android Equivalent Method is public void onMessageReceived(RemoteMessage remoteMessage)
#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());
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
handleNow();
}
}
// 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.
}
For reference see 1 2
PackageManager.getLaunchIntentForPackage is what you're looking for.
This is how you'd use it :-
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchIntent);

i want to start an activity/ app itself on onMessageReceived (FCM) when the App is not running in Android

On push message receive i want to start an activity / app itself on onMessageReceived (FCM) when the App is not running. How to start activity when onMessageReceived fired. Any help will be appreciated
You should send data payload in your FCM message. Data payload gets received in on message method irrespective of your app being in foreground or background. Handle the action there. Like show notification by reading the data payload always, or if you want show an alert dialog when your app is open or in the foreground.
here is a sample payload:
{
"to": "registration_id_or_topic",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
"youtubeURL": "https://youtu.be/A1SDBIViRtE"
}
}
Then in your onMessageReceived:
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
//Create or Start Your New Activity.
}
}

Push Notification Service is not running when the app is not in the background

I am a little bit confusing on integrating FCM (Firebase cloud messaging) push notification on my application.
Normally, Rather than the Intent services other services are not stopped anymore in the middle. I have created my message receiving service by extending to the FirebaseMessagingService as follow
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "NotificationBean Body: " + remoteMessage.getNotification().getBody());
//This method is responsible for handling notification
handleNotification(remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
}
and registered the service on manifest as follow:
<service android:name=".service.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
This service is run on when the app is live and running in the background too. But when the app is not in the background the service is not run anymore.
I have registered the service on Main Activity as follow
#Override
protected void onResume() {
super.onResume();
// register GCM registration complete receiver
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
// register new push message receiver
// by doing this, the activity will be notified each time a new message arrives
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
// clear the notification area when the app is opened
NotificationUtils.clearNotifications(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
}
Let me know anything wrong in my code. (Possibly not) .Why notifications are not running on background. How do I overcome this issue?
Thanks in advance.
use your server data or api like this
{
"to" : "deviceToken",
"notification" : {
"body" : "Pass body here",
"title" : "Title n",
"icon" : " icon ",
"sound" : "notification sound "
}
}
//for exa.
$fields=array('to'=>fdfdfdfdsfdsdfdfdsfdsfdfdsfd" ,'notification'=>array('title'=>'mytitle','body'=>$title,'click_action'=>'abc','icon'=>'ic_stat_final','sound'=>'default','color'=>'#00aff0'),'data'=>array('ghmid'=>$hgmid,'page'=>$page));
If your data is of type notification ie "Notification"then the onReceived method is not supposed to be get called when app is in background. Though it can be retrived when app comes to foreground. If it is of type data then it will get called.Change your type to "Data" instead of notification. Also when you change the data to type "Data" your getNotification() method may not work and app will get null pointer exception. Server data can also be of type where it has both "data" and "notification".
change json object key from notification to data
e.g
{
“to”: “device_ID/fcmID”,
“notification”: {
“body”: “great match!”,
“title”: “Portugal vs. Denmark”,
“icon”: “myicon”
}
}
change to
{
“to”: “device_ID/fcmID”,
“data”: {
“Nick”: “abc”,
“body”: “nfjwhhwruguig”,
“Room”: “cnrughwriugg”
},
}
Client app receives a data message in onMessageReceived() irrespective of the fact whether app is in foreground or background.
ref: https://blog.talentica.com/2017/01/20/firebase-cloud-messaging-in-android/

Firebase Cloud Messaging onMessageReceived not getting triggered

As instructed in Firebase dev docs, I've implemented a Service that extends FirebaseMessagingService and overrides the onMessageReceived callback. I have put a Log message in the first line inside the onMessageReceived method.
App running in background
I don't see the log in logcat but I see a Notification posted in the system try.
App in Foreground
I neither see the log nor the notification in system tray
Any idea what's going on?
Manifest
<service
android:name=".fcm.MovieMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Service Class
public class MovieMessagingService extends FirebaseMessagingService {
private static final String LOG_TAG = MovieMessagingService.class.getSimpleName();
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(LOG_TAG, "From: " + remoteMessage.getFrom());
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Log.d(LOG_TAG, "Presenting Notification with message body: " + messageBody);
//more code
}
}
Actually, app's behavior, while receiving messages including both notification and data payloads, depends on whether the app is in the background or the foreground like:
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.
When in the foreground, your app receives a message object with both payloads attached.
So, The summary is when app is in background, you can see the notification in system tray and can't see any log until tapping on the notification but you will see only the opening activity log not the service log as it's already executed.
And when the app in foreground you can see the log in logcat but you can't see any notification in the system tray as your app already open state you will receive only data payloads.
Here is a code example of how to receive messages and how to handle the different types. Here is the source of the code.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
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());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}

Categories

Resources