Firebase Messaging only works on separate devices - java

I am currently writing a feature for my app that allows the user to make a request to the worker in which they can accept or decline the job offer. I am using firebase messaging system. When I have two phones, the notification works and the worker can accept or decline, stated here:
public class MyFirebaseMessaging extends FirebaseMessagingService {
private static final String COLE_CHANNEL_ID = "com.example.usub.COLE";
#Override
public void onMessageReceived(RemoteMessage remoteMessage){
LatLng customer_location = new Gson().fromJson(remoteMessage.getNotification().getBody(),LatLng.class);
Intent intent = new Intent(getBaseContext(), CustomerCall.class);
intent.putExtra("lat", customer_location.latitude);
intent.putExtra("lng", customer_location.longitude);
intent.putExtra("customer", remoteMessage.getNotification().getTitle());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
However, I try to run the demo on my phone involving both apps, I receive the notification that the request has been made, however when the notification is clicked on, the app opens with no recollection of the data. My notification helper looks like this:
public class NotificationHelper extends ContextWrapper {
private static final String COLE_CHANNEL_ID = "com.example.usub.COLE";
private static final String COLE_CHANNEL_NAME = "STRADTMANNSOLUTIONS Usub";
private NotificationManager manager;
public NotificationHelper(Context base) {
super(base);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
createChannels();
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void createChannels() {
NotificationChannel coleChannels = new NotificationChannel(COLE_CHANNEL_ID,
COLE_CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
coleChannels.enableLights(true);
coleChannels.enableVibration(true);
coleChannels.setLightColor(Color.GRAY);
coleChannels.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getManager().createNotificationChannel(coleChannels);
}
public NotificationManager getManager() {
if(manager == null)
manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
return manager;
}
#RequiresApi(api = Build.VERSION_CODES.O)
public Notification.Builder getUsubNotification(String title, String content, PendingIntent contentIntent,
Uri soundUri)
{
return new Notification.Builder(getApplicationContext(),COLE_CHANNEL_ID)
.setContentText(content)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_notify);
}
}
Would anyone know why notification is losing all of its data or how I could open the app to a certain activity with new information from the press of a notification? Thank you

Notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. If app is in the background then a notification is shown but it will not trigger onMessageRecieved, and data from that message is passed to the intent that is launched.
And u can use:-
getIntent().getExtras();
to retrieve the data sent via notification.
Check the docs this

Related

audio player service stops when phone sleeps [duplicate]

This question already has answers here:
How can we prevent a Service from being killed by OS?
(11 answers)
Background service stops after 20 sec after destroy app in Android 10 java
(1 answer)
Closed 1 year ago.
I am running audio player service but If I put my phone on sleep the player stops or the background service I don't know what's the problem.
this is my music service class :
public class MusicService extends Service {
public static final String ACTION_NEXT = "NEXT";
public static final String ACTION_PREV = "PREVIOUS";
public static final String ACTION_PLAY = "PLAY";
public static final String ACTION_FORWARD = "FORWARD";
public static final String ACTION_REWIND = "REWIND";
public static final String ACTION_CONTINUE = "CONTINUE";
ActionPlaying actionPlaying;
Action action;
private final IBinder mBinder = new MyBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class MyBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String actionName = intent.getStringExtra("myActionName");
if (actionName != null) {
switch (actionName)
{
case ACTION_PLAY:
if(actionPlaying!= null){
if(action!= null){
actionPlaying.playClicked();
action.playPauseClicked();
}}
break;
case ACTION_NEXT:
if(actionPlaying != null){
actionPlaying.nextClicked();
}
break;
case ACTION_PREV:
if(actionPlaying != null){
actionPlaying.prevClicked();
}
break;
case ACTION_FORWARD:
if(actionPlaying != null){
actionPlaying.forwardClicked();
}
break;
case ACTION_REWIND:
if(actionPlaying != null){
actionPlaying.rewindClicked();
}
break;
case ACTION_CONTINUE:
Toast.makeText(this, "continue", Toast.LENGTH_SHORT).show();
action.continueMediaPlayer();
}
}
return START_STICKY;
}
public void setCallBack(ActionPlaying actionPlaying){
this.actionPlaying = actionPlaying;
}
public void setCallBack(Action action) {
this.action = action;
}
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
notificationManager.cancelAll();
saveData();
simpleExoPlayer.release();
}
}
and this is my media player initialization :
public void prepareMedia() {
isPlaying=true;
simpleExoPlayer = new SimpleExoPlayer.Builder(MediaPlayer_Activity.this).build();
MediaItem mediaItem = MediaItem.fromUri(audioUrl);
simpleExoPlayer.addMediaItem(mediaItem);
simpleExoPlayer.prepare();
simpleExoPlayer.seekTo(songPrevPosition);
}
Please tell me what's wrong LogCat is not showing anything I don't know how to stop this and where the problem is....
please help
After 9 Android version we have protections for simple service. Simple service can live 10 seconds, no more. You need to declare you service as Foreground Service. It will look like notification in status bar.
For fully information read documentation
according to Android Developers documentation :
You need to upgrade your background process to foreground inorder to make it live without needing your application to be visible to the user.
in order to change your service to foreground one, your service need to have a notification to inform the user that your music player service is working.
a simple foreground service code might look like this :
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Notification notification = buildStartingNotification();
startForeground(startId, notification);
...
return START_STICKY;
}
private Notification buildStartingNotification() {
int priority =NotificationCompat.PRIORITY_LOW;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
priority = NotificationManager.IMPORTANCE_LOW;
createNotificationChannel(priority);
}
Notification notification =
new Notification.Builder(this,CHANNEL_ID)
.setContentTitle("Your_notification_title")
.setContentText("Your_notification_description ")
.setSmallIcon(R.drawable.icon)
.setPriority(priority)
.build();
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel(int priority) {
CharSequence name = getText("Your_Channel_Name");
String description = getString("Your_Channel_Desc");
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, priority);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
N.B : if you're using application with (target_api > 26) you need to have also a notification channel which I included its code in createNotificationChannel, where your CHANNEL_ID could be any unique string id you want.
if you're wandering what's the meaning of notification channel ?
a notification channel is a mechanism built for android 8 or later to make the user turn off/on group of notification with same channel at once from setting.
as an example your application might have multiple notification channels (news/games/entertainment...etc), then the user can turn off news &games and leave only entertainment on.
First of all make sure you use foreground service. I suggest to you to start permanent notification like this:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationChannel channel;
Intent notifyIntent = new Intent(this, SomeActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = showStableMessage(this,
getString(R.string.app_desc),
"Message to user",
R.mipmap.ic_icon,
notifyPendingIntent);
startForeground(NotificationUtil.STABLE_CHANNEL_NOTIFY_ID, notification);
return Service.START_STICKY;
}
private Notification showStableMessage(Context context, String title, String message, int icon, PendingIntent intent) {
NotificationChannel channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel(STABLE_CHANNEL_ID,
STABLE_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(context, STABLE_CHANNEL_ID)
.setContentTitle(title)
.setContentText(Html.fromHtml(message)).setPriority(PRIORITY_DEFAULT)
.setSmallIcon(icon)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(intent)
.setCategory(NotificationCompat.CATEGORY_SERVICE).build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
return notification;
}
Second you have to put this in manifest:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
.....>
<service
android:name=".data.service.MyService"
android:foregroundServiceType="mediaPlayback"
android:enabled="true"/>
</application>

Group notification wont show

I am using FCM to send notifications between users when they receive a new message.
I had like to make a group notification from my app so it will show like this:
However, for some reason every new notification that I get, it deletes the other so it always shows only the latest notification.
My code is:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private FirebaseAuth auth;
private FirebaseFirestore db;
private static String GROUP_KEY = "NOTIFICATION";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
createNotificationChannel();
notifyThis(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"),remoteMessage.getData().get("var1"),remoteMessage.getData().get("var2"),remoteMessage.getData().get("var3"));
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "ABC";
String description = "ABCDE";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("191919", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void notifyThis(String title, String message, String var1, String var2, String var3) {
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra("ChatID",var1);
intent.putExtra("ReceiverID",var2);
intent.putExtra("itemID",var3);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "191919")
.setSmallIcon(R.drawable.ic_launcher_custom_background)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, mBuilder.build());
}
}
Is there any reason? Any chance that it is because of the channelId?
Also, I saw that I might need to build multiple notifications however how can I make it dynamic based on the amount of messages that the user gets?
Lets set I get 2 notifications and then I get one more message but I built only 2 notifications, how it will show me the third?
Thank you

Push notifications with no sound on MIUI

My app's main functionality is push-notification messages sent from remote server. I am using FCM as a message delivery service. My problem is that notifications come without any sound on Xiaomi Mi 9 Lite (Android 9/MIUI 11). However, on Xiaomi Redmi Note 5 (Android 9/MIUI 10) sound works fine and on Samsung Galaxy S7 Edge (Android 8) as well. I created MessagingService which extends FirebaseMessagingService and notification channel as written in documentation.
Here is my code:
public class MessagingService extends FirebaseMessagingService {
private static String channelId;
private NotificationManager notificationManager;
private NotificationChannel notificationChannel;
private NotificationCompat.Builder notificationBuilder;
private MessagesViewModel viewModel;
public MessagingService() { }
#Override
public void onCreate() {
super.onCreate();
channelId = getResources().getString(R.string.default_notification_channel_id);
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
final Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder = new NotificationCompat.Builder(this, channelId);
notificationBuilder.setSmallIcon(R.raw.metrial_message_icon);
notificationBuilder.setAutoCancel(false);
notificationBuilder.setSound(soundUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
final AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
String name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
notificationChannel = new NotificationChannel(channelId, name, importance);
notificationChannel.setDescription(description);
notificationChannel.enableLights(true);
notificationChannel.setShowBadge(true);
notificationChannel.setSound(soundUri, audioAttributes);
notificationManager.createNotificationChannel(notificationChannel);
notificationBuilder.setChannelId(channelId);
}
else {
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL);
notificationBuilder.setLights(Color.WHITE, 500, 5000);
}
viewModel = new MessagesViewModel(getApplication());
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
logger.info("onNewToken()");
ConnectionParameters.getInstance().setToken(s);
MyPrefs.getInstance(getApplicationContext()).putString(Constants.TOKEN, s);
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
final String messageId = remoteMessage.getData().get("message_id");
final String title = remoteMessage.getData().get("title");
final String body = remoteMessage.getData().get("body");
if (messageId != null && title != null && body != null) {
final Message message = new Message();
message.setMessageId(messageId);
message.setTitle(title);
message.setContent(body);
message.setTimestamp(new Date());
try {
message.setNotificationId((int)viewModel.insert(message));
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
logger.info("onMessageReceived(): notificationId=" + message);
if (MyPrefs.getInstance(getApplicationContext()).getBoolean(Constants.ENABLE_PUSH)) {
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(body);
final Intent notifyIntent = new Intent(this, MessageInfoActivity.class);
notifyIntent.putExtra(Constants.ARG_MESSAGE_OBJECT, message);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(notifyIntent);
PendingIntent pendingActivityIntent =
stackBuilder.getPendingIntent(message.getNotificationId(), PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingActivityIntent);
final Notification notification = notificationBuilder.build();
notification.defaults = Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS;
notificationManager.notify(message.getNotificationId(), notification);
}
}
}
private final Logger logger = LoggerFactory.getLogger(getClass());
}
And in Settings->Notifications I got the following parameters:
And inside my push-notifications-channel sound is enabled but whenever a message comes, it seems like app notification settings override parameters in notification channel.
There should be some solution because in popular apps such WhatsApp, Telegram, etc., these switches are enabled after installation (by default). Hope, someone helps!
As nobody provided better solution, I guess there is no way to allow sound/badge counter/floating notifications programmatically on MIUI (and mostly on other Chinese OEMs). It is a user's privilege to turn these settings on manually. Therefore, to enhance UX, it is important to decrease the quantity of "clicks" as much as possible. So, we could provide a dialog describing how to enable the features above with button leading to App's settings.
Namely, to open a notification settings page through Intent, do the following:
final Intent notificationSettingsIntent = new Intent();
notificationSettingsIntent
.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
notificationSettingsIntent
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationSettingsIntent.putExtra(
"android.provider.extra.APP_PACKAGE",
activity.getPackageName());
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationSettingsIntent.putExtra(
"app_package",
activity.getPackageName());
notificationSettingsIntent.putExtra(
"app_uid",
activity.getApplicationInfo().uid);
}
activity.startActivityForResult(
notificationSettingsIntent,
NOTIFICATIONS_SETTINGS_REQUEST_CODE);
and you could open a dialog with button "Open notification settings" clicking on which triggers the code snippet above.

Android Service stops broadcasting progress after a while

I have an Activity where the user can download a video. Upon user's click, the Download Service starts to download the content.
There is a progress bar in the Activity UI which I would like to update according to download progress in the service which broadcasts the progress periodically.
Everything works fine but after a certain time the service stops sending any broadcast progress, hence, the UI does not update anymore.
Additionally, how I can resume receiving the progress broadcast when the user goes to another Activity and comes back to this Activity? I mean, even if the above issue is solved, when the user presses back button and go to other activity and comes back to this activity, the progress gets lots. How can I check for any existing broadcast and receive it whenever the user comes to this activity.
In the ACTIVITY:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Log.d("DownloadService", "Progress Received In Activity");
Double progress = bundle.getDouble("PROGRESS");
updateDownloadProgressBar(progress);
}
}
};
private void startDownloadService() {
final String videoId = mItem.getAttributes().get(KEY_ASSET_ID);
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("VIDEOID", videoId);
startService(intent);
}
in the onResume():
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION_SERVICE));
in the onPause():
unregisterReceiver(receiver);
In the SERVICE:
private void publishProgress(double progress) {
Log.d(TAG, "Broadcasting progress from Service");
Intent intent = new Intent(NOTIFICATION_SERVICE);
intent.putExtra("PROGRESS", progress);
sendBroadcast(intent);
}
The download and progress work fine to 38% then stop.
It seems that the service is being stopped/killed from the OS, to avoid that use foreground service so you can make sure it will not be killed from the OS.
See the sample code below:
Service
public class PendingService extends Service {
private final static String TAG = "PendingService";
public final static int NOTIFICATION_ID = 94;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startInForeground();
// Do your work here ...
return START_STICKY;
}
private void startInForeground() {
String NOTIFICATION_CHANNEL_ID = "default";
String NOTIFICATION_CHANNEL_NAME = "My Pending Service";
String NOTIFICATION_CHANNEL_DESC = "This notification holding a pending task";
Intent notificationIntent = new Intent(this, SplashActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.notification)
.setOngoing(true)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
channel.setDescription(NOTIFICATION_CHANNEL_DESC);
channel.setSound(null, null);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
Notification notification = builder.build();
startForeground(NOTIFICATION_ID, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
removeNotification(NOTIFICATION_ID);
// ....
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void removeNotification(int notificationId) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(notificationId);
}
}
}
Utils you may need
class ServiceUtils {
/**
* #param service: Service to run
*/
fun startService(context: Context, service: Class<out Service>) {
val serviceIntent = Intent(context, service)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent)
} else {
context.startService(serviceIntent)
}
}
/**
* #return True: if the service is running
*/
fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
}

Open a different activity other than MainActivity when clicking Firebase Notification

In my application i want open custom activity (not MainActivity) and putExtra to this activity when click on Firebase notification.
I write below codes, but when click on notification open MainActivity, But i want open my another activity (AuctionDetailActivity).
My NotificationManager class :
public class MyNotificationManager {
private Context mCtx;
private Uri soundUri;
private static MyNotificationManager mInstance;
public MyNotificationManager(Context context) {
mCtx = context;
}
public static synchronized MyNotificationManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void displayNotification(String title, String body) {
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(mCtx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("fcm_notification", "Y");
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setSound(soundUri)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setContentText(body)
.setContentIntent(pendingIntent);
NotificationManager mNotifyMgr = (NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);
if (mNotifyMgr != null) {
mNotifyMgr.notify(1, mBuilder.build());
}
}
}
And MyFirebaseMessagingService class :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
showNotify(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
}
private void showNotify(String title, String body) {
MyNotificationManager myNotificationManager = new MyNotificationManager(getApplicationContext());
//myNotificationManager.displayNotification(title, body);
myNotificationManager.displayNotification(title, body);
}
}
MainActivity codes:
#Override
protected void onResume() {
super.onResume();
String fcm_notification = getIntent().getStringExtra("fcm_notification");
Log.d("FireBaseIntentLog", " FCM : " + fcm_notification);
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d("FireBaseIntentLog", "Key: " + key + " Value: " + value + " FCM : " + fcm_notification);
}
}
}
How can i fix it?
If you are sending the notification from Firebase console or inside the notification field using FCM API, the app behaves in two ways -
If your app is in foreground, the method onMessageReceived of your FCM service class will be called.
If your app is in background, nothing will happen inside your FCM service class. Rather, the notification will be handled internally by the FCM library itself and the notification with launcher activity in the intent will be shown.
And if you use FCM API to send notification and use the data field, the library does nothing itself and instead calls the method onMessageReceived regardless of whether your app is in foreground or background.
So in order to solve your issue, you can use one of the following two solutions:
Use FCM API to send notifications and use the data field instead of the notification field. Check the documentation to read more about FCM API.
In your launcher (main) activity, check for intent inside onCreate and if it is coming from notification, read the extras, finish the main activity and open your required activity.
Example for second case:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkIntent()) return;
// other code.
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkIntent();
}
private boolean checkIntent() {
// to receive the value, send the value as custom data from Firebase console.
String value = getIntent().getStringExtra("your_key");
if (value == null) return false;
if (value.equals("something")) {
// open one activity.
} else if (value.equals("another_thing")) {
// open another activity.
}
finish();
return true;
}
Change this below line
Intent intent = new Intent(click_action);
to this
Intent intent = new Intent(getActivity(), YourClass.class);
You just need modify in sendNotification function
public void sendNotification(String messageBody, String messageTitle, int user_id, String click_action) {
Intent intent = new Intent(mCtx, AuctionDetailActivity.class); // Need modify this line
intent.putExtra(Extras.bidID.name(), user_id);
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
Change your MyFirebaseMessagingService class as shown below replace OtherApp.class with your activity name
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent=new Intent(this,OtherApp.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);//newbg PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder= new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle("FCM NOTIFICATION"); notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}

Categories