I receive notifications from Firebase but my classes I've created not working (not involved in the actions). Seems like they are shown by default.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
Intent intent = new Intent(click_action);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notifiBuilder.build());
}
}
There are two types of FCM messages: notification and data. They are handled differently in the receiving device. If you are sending a notification message with no data fields, the notification is generated by the client SDK and onMessageReceived() is not invoked. This is explained in more detail in the documentation:
Notification Message: FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages
have a predefined set of user-visible keys and an optional data
payload of custom key-value pairs.
Data Message: Client app is responsible for processing data messages. Data messages have only custom key-value pairs.
Related
In the Firebase Cloud Messaging documentation, nothing mentioned about the notifications with big view/expanded layout.
How should I display big view notifications when app is background? Creating custom notification in FirebaseMessagingService's onMessageReceived seems not possible according to this faq:
When your app is in the background, notification messages are displayed in the system tray, and onMessageReceived is not called. For notification messages with a data payload, the notification message is displayed in the system tray, and the data that was included with the notification message can be retrieved from the intent launched when the user taps on the notification.
Send the notification you want to see using the data object. You can basicly put everything you want in the data object and always receive it at the onMessageReceived method. Here's an example.
public class AppFireBaseMessagingService extends FirebaseMessagingService {
private final static int REQUEST_CODE = 1;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
if (data == null) return;
if (data.containsKey("title") && data.containsKey("message")) {
showNotification(data.get("title"), data.get("message"));
}
}
private void showNotification(String title, String body) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setSmallIcon(R.drawable.notification_icon);
if (body != null && !body.isEmpty()) {
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(body));
builder.setContentText(body);
}
Intent intent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = builder.build();
n.defaults = Notification.DEFAULT_ALL;
notificationManager.notify(0, n);
}
}
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
I'm trying to send a push notification from the Firebase console, currently I can send a message from my Firebase console to my virtual device, but if the message is long it will not be fully displayed in the notification bar.
This is the code for the Firebasemessagingservice:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.RemoteMessage;
/**
* Created by filipp on 5/23/2016.
*/
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
showNotification(remoteMessage.getData().get("message"));
}
private void showNotification(String message) {
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("Elit")
.setContentText(message)
//.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
}
Thanks Adib for the detailed answer, I already have a PHP backend server but whenever I try to send a long notification from the server it will not display fully, my question is can I only edit the last part of the code so I can send long notifications from my server either using inboxStyle or bigtextstyle.
private void showNotification(String message) {
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("Elit")
.setContentText(message)
//.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
Referring to this link, you still cannot send Push notification via Firebase in big notification style. It'll always be in s simple single notification style, unless Firebase Library adds this feature and starts supporting it.
However, you can tweak it to work in your way. But point to be noted, this process is not possible if you're sending data via the Notification section of your Firebase Project console. This can be done only if your app has a backend and push notification is sent via web.
Send notification data in your payload using the "data" key, not the "notification" key. This makes sure the onMessageReceived(RemoteMessage remoteMessage) method in FirebaseMessagingService class is always triggered anytime a push is received. If you send data in "notification" key and if your app is not open, it'll be handled automatically by your app in simple notification style (which is not what we want).
Now that we've made sure all push data comes directly to our onMessageReceived(RemoteMessage remoteMessage) method in FirebaseMessagingService class without creating a Notification all by it's own, you need to create a Notification out of the data received. Here's a sample code attached to serve that purpose:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, whatToOpen, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setAutoCancel(true)
.setSmallIcon(R.drawable.push_icon_small)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.drawable.push_icon_large))
.setSound(defaultSoundUri)
.setColor(getResources().getColor(R.color.colorPrimary))
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
This part is what makes the notification big.
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
Now you can even send an article in your push notifications! Hope this helps!
I implemented Google Cloud Messaging in my Android app. When I send a message with JSON while I have opened the app, it acts different than when I have the app closed.
When I have the app open, and receive the notification, it starts the intent I want it to start. When I have the app closed when i receive the notification, and I click on the notification, it opens the Main intent. How can I say which intent it needs to open when I have closed my app and receive the push notification?
The code in MyGcmListenerService
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
File fileDir, file;
String filename, filestring;
/**
* Called when message is received.
*
* #param from SenderID of the sender.
* #param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
#Override
public void onMessageReceived(String from, Bundle data) {
Bundle notification = data.getBundle("notification");
String title = notification.getString("title");
String naam = notification.getString("naam");
String nfcId = notification.getString("nfcId");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Title: " + title);
Log.d(TAG, "Naam: " + naam);
Log.d(TAG, "nfcId: " + nfcId);
if (from.startsWith("/topics/")) {
} else {
filename = "gegevensOverledene";
ReadWriteFile readWriteFile = new ReadWriteFile(getApplicationContext());
readWriteFile.writeFileOverledene(filename, naam);
}
sendNotification(title, naam, nfcId);
}
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String naam, String nfcId) {
Intent intent = new Intent(this, PinLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("naam", naam);
intent.putExtra("nfcId",nfcId);
intent.putExtra("Class",NieuweOverledeneActivity.class);
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)
.setContentTitle(title)
.setContentText(naam)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
The JSON I send, note that I left out the token_mobile on purpose
{
"to": "TOKEN_MOBILE****************",
"notification": {
"title": "Nieuwe overledene",
"body": "Henk",
"naam": "Henk",
"nfcId": "80-40-A3-4A-C2-D6-04"
}
}
You are sending a notification message. See more on how notification messages are to be handled here.
When your app is in the foreground notification messages are passed to your onMessageReceived callback. There you can decide what should be done with the received message, eg: generate and display a notification or sync with your app server or whatever.
When your app is in the background notification messages automatically generate notifications based on the properties passed in the "notification" object of your downstream message request, onMessageReceived is not called in this case. If you look at the reference docs for notification messages you will see a field named click_action you can use this to define what Activity is launched when the automatically generated notification is tapped:
On Android, if this is set, an activity with a matching intent filter
is launched when user clicks the notification.
If this is not set the main Activity is launched, which is what you are seeing now.
Note: This behaviour is only for Notification Messages, if you send data only messages then all sent messages will result in onMessageReceived being called.
check Following
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String naam, String nfcId) {
//Create the intent according to your condition and pass it to pendingintent.
Intent intent = new Intent(this, PinLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("naam", naam);
intent.putExtra("nfcId",nfcId);
intent.putExtra("Class",NieuweOverledeneActivity.class);
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)
.setContentTitle(title)
.setContentText(naam)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
I setup GCM and it works fine. I get notifications from the server and they are shown to the client. The problem is, GCM creates its own notification and wont let me make a custom one. I followed this guide: https://github.com/codepath/android_guides/wiki/Google-Cloud-Messaging.
Here is my service code:
public class GcmMessageHandler extends GcmListenerService {
public static final int MESSAGE_NOTIFICATION_ID = 435345;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
createNotification(from, message);
}
private void createNotification(String title, String body) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true);
Intent resultIntent = new Intent(this, RouteActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(RouteActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
}
}
Anything helps.
from the docs
Message payload is optional. If you are including a payload in the message, use the data parameter to include your custom key/value
pairs. The client app handles the data payload for display or other
processing purposes.
The notification parameter with predefined options indicates that GCM
will display the message on the client app’s behalf if the client app
implements GCMListenerService on Android, or whenever the notification
message is sent to an iOS device. The app server can send a message
including both notification and data payloads. In such cases, GCM
handles displaying the notification payload and the client app handles
the data payload. For more information and examples, see
in other words if you send in your payload a notification tag GCM will create a notification for your app
https://developers.google.com/cloud-messaging/server
Custom layout for notifications in Android, if that's what you mean: Create custom notification, android