I try to execute a function in my MainActivity when a notification is clicked.
The function needs a data that I put in intent extras.
The problem is when I click the notification when the application is running the function is executed, but when I click the notification when the application is in the background, the function isn't executed. I've checked it and it's because the data that I put in intent extras is empty when the application is in the background.
How can I solve this problem? Thanks!
This is the response i receive :
{
"to":"blablabla",
"notification": {
"body":"Sentiment Negative from customer",
"title":"Mokita"
},
"data" : {
"room_id":1516333
}
}
This is my notification code :
public void onMessageReceived(RemoteMessage message) {
super.onMessageReceived(message);
Log.d("msg", "onMessageReceived: " + message.getData().get("room_id"));
String roomId = message.getData().get("room_id");
Intent intent = new Intent(this, HomePageTabActivity.class);
intent.putExtra("fromNotification", true);
intent.putExtra("roomId", roomId);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(message.getNotification().getTitle())
.setContentText(message.getNotification().getBody())
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}
And this is the function and how i executed it in MainActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
onNewIntent(getIntent());
}
#Override
public void onNewIntent(Intent intent){
Bundle extras = intent.getExtras();
if(extras != null){
if(extras.containsKey("fromNotification") || extras.containsKey("roomId")) {
openChatRoom(Long.valueOf(extras.getString("roomId")));
}else if(extras.containsKey("fromNotification") && extras.containsKey("roomId")){
openChatRoom(Long.valueOf(extras.getString("roomId")));
}else{
Log.e("EXTRAS room",""+extras.getString("roomId"));
Log.e("EXTRAS STATUS",""+extras.getBoolean("fromNotification"));
}
}else{
Toast.makeText(HomePageTabActivity.this,"Empty",Toast.LENGTH_SHORT).show();
}
}
public void openChatRoom(long roomId){
Log.d("LONG ROOM",""+roomId);
QiscusRxExecutor.execute(QiscusApi.getInstance().getChatRoom(roomId),
new QiscusRxExecutor.Listener<QiscusChatRoom>() {
#Override
public void onSuccess(QiscusChatRoom qiscusChatRoom) {
startActivity(GroupRoomActivity.
generateIntent(HomePageTabActivity.this, qiscusChatRoom));
}
#Override
public void onError(Throwable throwable) {
throwable.printStackTrace();
}
});
}
Firebase has two types of messages: notification messages and data messages. If you want FCM SDK to handle the messages by its own, you need to use notification. When the app is inactive, FCM will use notification body to display the messages. In this state, onMessageReceived also will not be triggered. If you want app to process the messages, you need to use data. You might need to change push notification payload from
{
"message":{
"token":"xxxxx:...",
"notification":{
"title":"Your title",
"body":"Your message"
}
}
}
to
{
"message":{
"token":"xxxxx:...",
"data":{
"title":"Your title",
"body":"Your message",
"fromNotification":"true",
"roomId":"123"
}
}
}
You also need to process the messages in onMessageReceived(RemoteMessage remoteMessage) accordingly. You can read about notification behaviour in Notifications and data messages.
these payloads will be delivered to the activity you are specifying in the pending intent. so when the user clicks on your notification, HomePageTabActivity launches and you can get the intent by calling getIntent() anywhere in activity lifecycle. but because you are setting singleTop flag on activity if HomePageTabActivity is already launched, Android will not launch it again and will pass the new Intent (provided in notification) to onNewIntent() instead. you can consume it there or even call the getIntent() to get the new value from there on.
Receive messages in an Android app. Messages with both notification and data payload, both background and foreground. In this case the data payload is delivered to extras of the intent of your launcher activity. If you want to get it on some other activity, you have to define click_action on the data payload. So get the intent extra in your launcher activity.
Related
I'm sending firebase-messages using the firebase-console. The messages shall contain additional data like shown below with the purpose to open a specific URL within a webview in my app:
I set up my manifest and firebase class to get the messages. Within my firebase class I try to get the data:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(remoteMessage.getData().containsKey("key1")) {
intent.putExtra("destination", remoteMessage.getData().get("key1"));
}
PendingIntent pendingIntent = PendingIntent.getActivity
(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String channelId = "default";
NotificationCompat.Builder builder;
if (remoteMessage.getNotification() != null ) {
if (remoteMessage.getNotification().getTitle() != null) {
builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_onesignal_default)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
} else {
builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_onesignal_default)
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
}
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "default", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}
Within my MainActivity class I try to get the data. When the app is in the foreground, the following works (no matter what activity is opened, it will jump to the MainActivity and execute the following):
#Override
protected void onNewIntent(Intent intent) {
if (intent.getExtras() != null) {
Bundle extras = intent.getExtras();
if(extras.containsKey("destination")) {
Log.e("FIREBASE_CONTAINS", (String) extras.get("destination"));
}
}
}
But the event wont trigger if the app started from the background. I tried to get the intent and check for the key within the onResume() event of the activity, but it does not work (Same in inCreate() and onStart()).
Can anybody help me?
------------EDIT-----------------
As described in one of the comments, the problem seems to be that Notification-Messages won't reach the onMessageReceived() event. Apparently the firebase console can't send data-notifications (which would reach the event) so I tried using POSTMAN. I've read that I have to leave the notification tag out of the message body and put all my information in the data section. But if I do so, the messages won't reach my app (they do, when I add the notification section again, but of course they are not reaching the onMessageReceived() event in that case).
There are 3 types of push messages
notification
data
and both
A push messages is basically a json payload:
payload:{
notificacion...
data
}
Rules for each type of push messages are differente. In your case you are using the Firebase web console and adding custom data, which mean your payload will have notification and data.
For the combined type the behaviour in backgroun is to use a default notificacion (NotificationCompat, the visual kind) and open the default activity registered in the manifest. In the activity you can get the data.
Lets say your default activity is called MainActivity
public class MainActivity {
onCreate...{
//... usual stuff
Intent fcmIntent = getIntent();
if fcmIntent != null
//check the extras and forward them to the next activity if needed
}
}
There are two type of push message
(1)Notification Message (will receive when app is in foreground)
(2)Data Message (will receive when app is in background+foreground)
Reference : https://firebase.google.com/docs/cloud-messaging/android/receive
You need to set click_action in firebase notification data set to be able to receive data from background and implement onMessageReceived to handle foreground data
See updated answer here: https://stackoverflow.com/a/73724040/7904082
My Android application gets firebase notifications. And I need to localize this notifications depends on application language on the client side, not on server side.
If application is in foreground I use onMessageReceived() from FirebaseMessagingService and push my own localized notification. But if application is in background onMessageReceived() doesn't called.
In this case I use my own class extended BroadcastReceiver. onReceive(Context context, Intent intent) method catches notification, I localize it and push. Everything goes good, but in the end I get 2 push notifications: my own localized and firebase.
How can I get rid of this firebase notification and get only my own?
public class FirebaseDataReceiver extends BroadcastReceiver {
Context context;
PendingIntent pendingIntent;
public void onReceive(Context context, Intent intent) {
this.context = context;
Bundle dataBundle = intent.getExtras();
String title = "";
String body = "";
String type = "";
String objectId = "";
if (dataBundle != null) {
type = dataBundle.getString("type");
objectId = dataBundle.getString("objectId");
title = NotificationUtils.getNotificationTitle(context, dataBundle);
body = NotificationUtils.getNotificationBody(context, dataBundle);
}
Intent newIntent = new Intent(context, TutorialActivity_.class);
newIntent.putExtra("target", "notification");
newIntent.putExtra("type", type);
newIntent.putExtra("objectId", objectId);
newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context,
0,
newIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(context)
.setContentTitle(title)
.setContentText(body)
.setPriority(Notification.PRIORITY_HIGH)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.splash_mini)
.build();
deleteLastNotification();
NotificationManagerCompat.from(context).notify(0, notification);
}
}
You should really use Data notifications from the server. Normal message notifications can't achieve this behaviour you're looking for. Check out the docs here:https://firebase.google.com/docs/cloud-messaging/concept-options
So your request to Firebase from the server should look something like this:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
Instead of:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
I am developing an Android application which calls API's to fetch data. Now I want to perform this task in background and each time data is changed in the List view, a notification should be generated.
How can I achieve this?
How can I make my API called in background and how can i generate notification.
I am new to Services and BroadcastReceivers so help me
I am calling the service this way:
startService(new Intent(this, MyService.class).putExtra("Background",true));
I created this code to testing purpose. To check if notifications can be called in background even if the app is closed.
My Service Class
public class MyService extends Service {
private Boolean isShowingNotification = true ;
NotificationManager notificationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (intent.hasExtra("Background")) {
if (isShowingNotification) {
StopImportantJob();
stopSelf();
} else
DoImportantJob();
} else {
DisplayNotification("Now showing the demo");
}
return START_NOT_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Toast.makeText(this, "On Create Called", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
super.onDestroy();
notificationManager.cancelAll();
}
public void DisplayNotification(String message){
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notification = new Notification.Builder(this)
.setContentTitle(message)
.setContentText("Touch to off Service")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setOngoing(false)
.build();
notificationManager.notify(0,notification);
}
public void DoImportantJob(){
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notification = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setOngoing(false)
.build();
startForeground(1992, notification);
isShowingNotification =true;
}
public void StopImportantJob(){
stopForeground(true);
isShowingNotification = false;
if(false){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ){
stopForeground(STOP_FOREGROUND_DETACH);
stopForeground(STOP_FOREGROUND_REMOVE);
}
}
}
}
What I believe I should do is listed below, please correct me if I am wrong.
Start Service in the onCreate() of the MainAcitivity of Application.
In the Service call I will create a method which will do the API call.
On notifyDataSetChanged(); will call the Notification method.
Now here is the question: In Service class the API method will be called in onCreate() or onStartCommand().
Now i want to perform this task in background and each time data is
changed in the List view, a notification should be generated. How can
i achieve this? How can i make my API called in background and how can
i generate notification.
First Decide, whether you want this operation when your application is in Foreground OR Background. Now, if Foreground, you might not want to use Service class and use AsyncTask instead for making your webservice calls and generate the notification and updatethe listview once task is done. If Background, you can create IntentService and do your API operation there. However, in background mode, your application do not need to be notified as your app will not be visible to client.
i'm want to do long background work
also i want to be able to show progress with statistics in ui anytime user goes to a activity also with updating notification.
i start a Service in START_STICKY mode then i bind it to my activity and run the proccess with an public method of Service.
everything works well until i close my app from recent apps.
it destroys and restart my running Service.
that's the problem. "i don't want my running service to restart"
i want my service to keep running without termination and without restarting.
how can i do what i want to do?
why os restart a running service: / thou
i tried START_NOT_STICKY but it's closing the service too.
On Android 6+, a foreground service will not be stopped when the user removes the app from recents. You can make your service a foreground service by adding this code to onCreate():
final Intent launcherIntent = new Intent();
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launcherIntent, 0);
final Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Test Notification")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
final Notification notification;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notification = builder.build();
}
else {
//noinspection deprecation
notification = builder.getNotification();
}
this.startForeground(NOTIFICATION_ID, notification);
Prior to Android 6, services are always killed when the user removes the task from recents. There is nothing you can do about it except shut down cleanly in onTaskRemoved().
Try using foreground service:
In method where you start service:
Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(startIntent);
Now in onStartCommand():
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
Read more Simple foreground service
OR you can try something like this:
from onStartCommand() need to return START_STICKY
override in your service onDestroy method:
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("broadcast.Message", "alarm, need to restart service");
sendBroadcast(broadcastIntent);
}
Now need to implement broadcast receiver:
public class RestarterBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startService(new Intent(context, YourService.class));
}
}
check if service is running or not
if(!isBackgroundServiceRunning(BackgroundServices.class))
{
Intent intent = new Intent(this,BackgroundServices.class);
startService(intent);
}
private boolean isBackgroundServiceRunning(Class<?> service)
{
ActivityManager manager = (ActivityManager)(getApplicationContext().getSystemService(ACTIVITY_SERVICE));
if (manager != null)
{
for(ActivityManager.RunningServiceInfo info : manager.getRunningServices(Integer.MAX_VALUE))
{
if(service.getName().equals(info.service.getClassName()))
return true;
}
}
return false;
}
I have added two actions to the notification i.e. accept and reject.
I can see both when the app is in foreground. But I cant see the actions when app is in background.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private String mOrderId, mBillId;
private Boolean mUpdateNotification;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
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.describeContents());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
//get data from server notification.
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
}
//send notification
private void sendNotification(String messageBody, String title) {
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent,
PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {500, 500, 500, 500, 500};
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.login_logo_1)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setSound(defaultSoundUri)
.addAction(R.string.accept,getString(R.string.accept), pendingIntent)
.addAction(R.string.reject,getString(R.string.reject), pendingIntent)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 , notificationBuilder.build());
}
}
Also I want to handle the intents from these actions. For this I have created a class which extends broadcast receiver,but how to call this in an activity?
public class NotificationReceiver extends BroadcastReceiver {
String ACCEPT,REJECT;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(ACCEPT.equals(action)) {
Log.v("Delivery","Accepted");
}
else if(REJECT.equals(action)) {
Log.v("Delivery","Rejected");
}
}
}
Please help. Thank you..
In FCM there are three type of messages you can send
1. 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.
Use notification messages when you want FCM to handle displaying a
notification on your client app's behalf.
2.Data message
Client app is responsible for processing data messages. Data messages
have only custom key-value pairs.
Use data messages when you want to process the messages on your
client app.
3. Both Notification and Data
Messages with both notification and data payload, both background and
foreground. In this case, 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.
So if you want to handle message on client side better you go with Data Message
here you get all details
For send Data Message
For Data Message you have to call post service using following URL
https://fcm.googleapis.com/fcm/send
Headers
Authorization:key=yourserverkey
Content-Type: application/json
Payload
{"data": "extra data to be send",
"to" : "devicetoken"
}
Note: replace "to" with "registration_ids" : ["1","2","3","4","5","6"] for multiple devices
In Application onMessageReceived you can get data message using remoteMessage.getData()
For detail already mentioned this https://firebase.google.com/docs/cloud-messaging/concept-options
Here you also check to send notification to Topics using data message https://firebase.google.com/docs/cloud-messaging/android/topic-messaging