Reputation: 12464
A FCM message can have one of data
, notification
or both. The notification that system generates using notification
lacks functionalities, so I removed notification
and sent data
only. Therefore, I have to create notifications myself.
Creating and showing notifications was easy, but I do not want to show a notification when my app (specifically MainActivity, but it has only one activity, anyway) is already on the foreground. Most apps do not show notifications when they are on the foreground.
How do I know in onMessageReceived
if my app is not on the foreground?
class MessagingService : FirebaseMessagingService()
{
override fun onMessageReceived(remoteMessage: RemoteMessage?)
{
// Check if message contains a data payload.
if (remoteMessage?.data?.isNotEmpty() == true)
{
//Log.d(TAG, "Message data payload: " + remoteMessage.data)
......
if "Only when my app is on the background or not running?"
sendNotification("Got a message.")
}
}
Upvotes: 1
Views: 823
Reputation: 117
/**
* Method checks if the app is in background or not
*
* @param context Application context
* @return True/False
*/
public static boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
Upvotes: 2