Android notification is not showing in the background

Viewed 90

app is open Notification is showing but app is in the background Notification is not showing The notification should be working 8 , but android 9,10 not working. The Notification isn't showing at all. I don't know what am I missing.

this is a MyFCMservise file

class MyFCMService : FirebaseMessagingService() {
    private var fireManager = FireManager()
    private var disposables = CompositeDisposable()
    private lateinit var newMessageHandler: NewMessageHandler

    private val parentJob = SupervisorJob()
    private val scope = CoroutineScope(Main + parentJob)


   

    


    override fun onNewToken(s: String) {
        super.onNewToken(s)
        if (!isLoggedIn()) return 


        SharedPreferencesManager.setTokenSaved(false)
        ServiceHelper.saveToken(this, s)
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        if (FireManager.isLoggedIn()
                .not()
        ) return  
        if (updateChecker.needsUpdate()) return

        val mainHandler = Handler(mainLooper)
        //run on main thread
        val myRunnable = Runnable {
            newMessageHandler = NewMessageHandler(this, fireManager, messageDecryptor, disposables)



            if (remoteMessage.data.containsKey("event")) {
                
                when {
                    remoteMessage.data["event"] == "group_event" -> {
                        handleGroupEvent(remoteMessage)
                    }
                    remoteMessage.data["event"] == "new_group" -> {
                        handleNewGroup(remoteMessage)
                    }
                    remoteMessage.data["event"] == "message_deleted" -> {
                        handleDeletedMessage(remoteMessage)
                    }
                    remoteMessage.data["event"] == "new_call" -> {
                        handleNewCall(remoteMessage)
                    }

                    remoteMessage.data["event"] == "logout" -> {
                        val newDeviceId = remoteMessage.data["deviceId"]

                        if (newDeviceId != null && newDeviceId != DeviceId.id) {
                            LocalBroadcastManager.getInstance(this)
                                .sendBroadcast(Intent(IntentUtils.ACTION_LOGOUT))
                            FireManager.logout()
                            NotificationHelper(this).fireUserLoggedOutNotification()
                        }
                    }

                }
            } else {
                if (remoteMessage.data.containsKey(DBConstants.MESSAGE_ID)) {
                    handleNewMessage(remoteMessage)
                }
            }
        }
        mainHandler.post(myRunnable)
    }

    private fun handleNewCall(map: RemoteMessage) {
        val data = map.data

        data["callId"]?.let { callId ->


            val fromId = data["callerId"] ?: ""

            val typeInt = data["callType"]?.toIntOrNull() ?: CallType.VOICE.value
            val type = CallType.fromInt(typeInt)


            val groupId = data["groupId"] ?: ""

            val isGroupCall = type.isGroupCall()

            if (!isGroupCall && uid.isEmpty()) return@let
            if (isGroupCall && groupId.isEmpty()) return@let
            val channel = data["channel"] ?: return@let

            val groupName = data["groupName"] ?: ""

            val timestamp = data["timestamp"]?.toLongOrNull() ?: System.currentTimeMillis()
            val phoneNumber = data["phoneNumber"] ?: ""

            val isVideo = type.isVideo()

            val uid = if (isGroupCall) groupId else fromId


            var user: User

            val storedUser = RealmHelper.getInstance().getUser(uid)

            if (storedUser == null) {
                //make dummy user temporarily
                user = User().apply {
                    if (isGroupCall) {
                        this.uid = groupId!!
                        this.isGroupBool = true
                        this.userName = groupName
                        this.group = Group().apply {
                            this.groupId = groupId
                            this.isActive = true
                            this.setUsers(mutableListOf(SharedPreferencesManager.getCurrentUser()))
                        }

                    } else {
                        this.uid = uid
                        this.phone = phoneNumber
                    }
                }
            } else {
                user = storedUser
            }

            val fireCall = FireCall(
                callId,
                user,
                FireCallDirection.INCOMING,
                timestamp,
                phoneNumber,
                isVideo,
                typeInt,
                channel
            )


            newMessageHandler.handleNewCall(fireCall)

        }

    }

    private fun handleNewMessage(remoteMessage: RemoteMessage) {
        val messageId = remoteMessage.data[DBConstants.MESSAGE_ID]

        //if message is deleted do not save it
        if (RealmHelper.getInstance().getDeletedMessage(messageId) != null) return
        if (RealmHelper.getInstance().getTempMessage(messageId) != null) return


        val isGroup = remoteMessage.data.containsKey("isGroup")
        //getting data from fcm message and convert it to a message
        val phone = remoteMessage.data[DBConstants.PHONE] ?: ""
        val content = remoteMessage.data[DBConstants.CONTENT]
        val timestamp = remoteMessage.data[DBConstants.TIMESTAMP]
        val type = remoteMessage.data[DBConstants.TYPE]?.toInt() ?: 0
        //get sender uid
        val fromId = remoteMessage.data[DBConstants.FROM_ID]
        val toId = remoteMessage.data[DBConstants.TOID]
        val metadata = remoteMessage.data[DBConstants.METADATA]
        val partialText = remoteMessage.data[DBConstants.PARTIAL_TEXT]

        

        //if it's a group message and the message sender is the same
        if (fromId == uid) return

        //create the message
        val message = Message()
        message.content = content
        message.partialText = partialText
        message.timestamp = timestamp

        message.fromId = fromId
        message.type = convertedType
        message.messageId = messageId
        message.metadata = metadata
        message.toId = toId
        val chatId = if (isGroup) toId else fromId
        message.chatId = chatId
        message.isGroup = isGroup
        if (isGroup) message.fromPhone = phone
        //set default state
        message.downloadUploadStat = DownloadUploadStat.FAILED

       
        if (MessageType.isSentText(type)) {
            //set the state to default
            message.downloadUploadStat = DownloadUploadStat.DEFAULT
} else if (remoteMessage.data.containsKey(DBConstants.LOCATION)) {


            message.downloadUploadStat = DownloadUploadStat.DEFAULT
            //get the json location as String
            val lat = remoteMessage.data["lat"] ?: ""
            val lng = remoteMessage.data["lng"] ?: ""
            if (lat.isNotEmpty() && lng.isNotEmpty()) {
                val name = remoteMessage.data["name"] ?: ""
                val address = remoteMessage.data["address"] ?: ""
                val location = RealmLocation(address, name, lat, lng)
                message.location = location
            }
        } else if (remoteMessage.data.containsKey(DBConstants.THUMB)) {
            val thumb = remoteMessage.data[DBConstants.THUMB]

            //Check if it's Video and set Video Duration
            if (remoteMessage.data.containsKey(DBConstants.MEDIADURATION)) {
                val mediaDuration = remoteMessage.data[DBConstants.MEDIADURATION]
                message.mediaDuration = mediaDuration
            }
            message.thumb = thumb


            //check if it's Voice Message or Audio File
        } else if (remoteMessage.data.containsKey(DBConstants.MEDIADURATION)
            && type == MessageType.SENT_VOICE_MESSAGE || type == MessageType.SENT_AUDIO
        ) {

            //set audio duration
            val mediaDuration = remoteMessage.data[DBConstants.MEDIADURATION]
            message.mediaDuration = mediaDuration

            //check if it's a File
        } else if (remoteMessage.data.containsKey(DBConstants.FILESIZE)) {
            val fileSize = remoteMessage.data[DBConstants.FILESIZE]
            message.fileSize = fileSize
        }

        
        if (remoteMessage.data.containsKey("quotedMessageId")) {
            val quotedMessageId = remoteMessage.data["quotedMessageId"]
            
            RealmHelper.getInstance().refresh()
            val quotedMessage = RealmHelper.getInstance().getMessage(quotedMessageId, chatId)
            if (quotedMessage != null)
                message.quotedMessage = QuotedMessage.messageToQuotedMessage(quotedMessage)
        }

        
        if (remoteMessage.data.containsKey("statusId")) {
            val statusId = remoteMessage.data["statusId"]
            
            RealmHelper.getInstance().refresh()
            val status = RealmHelper.getInstance().getStatus(statusId)
            if (status != null) {
                message.status = status
                val quotedMessage = Status.statusToMessage(status, fromId)
                quotedMessage?.fromId = uid
                quotedMessage?.chatId = fromId
                if (quotedMessage != null)
                    message.quotedMessage = QuotedMessage.messageToQuotedMessage(quotedMessage)


            }
            
        }


        scope.launch(Main) {
            newMessageHandler.handleNewMessage(phone, message)
        }


    }

    private fun handleDeletedMessage(remoteMessage: RemoteMessage) {
        newMessageHandler.handleDeletedMessage(remoteMessage.data)
    }

    private fun handleNewGroup(remoteMessage: RemoteMessage) {
        newMessageHandler.handleNewGroup(remoteMessage.data)
    }

    private fun handleGroupEvent(remoteMessage: RemoteMessage) {
        newMessageHandler.handleGroupEvent(remoteMessage.data)
    }


    override fun onDestroy() {
        super.onDestroy()
        disposables.dispose()
        cancelCoroutineJob()
    }

    private fun cancelCoroutineJob() = try {
//        parentJob.cancel()
    } catch (e: Exception) {
    }
}



Notification Builder



public class NotificationHelper extends ContextWrapper {

    
    

    private NotificationManager manager;


    public NotificationHelper(Context base) {
        super(base);
        
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            NotificationChannel messagesChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_MESSAGES,
                    NOTIFICATION_CHANNEL_NAME_MESSAGES, NotificationManager.IMPORTANCE_HIGH);

            messagesChannel.setVibrationPattern(getVibrationPattern());
            getManager().createNotificationChannel(messagesChannel);

            NotificationChannel audioChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_AUDIO,
                    NOTIFICATION_CHANNEL_NAME_AUDIO, NotificationManager.IMPORTANCE_HIGH);
            audioChannel.setSound(null, null);

            getManager().createNotificationChannel(audioChannel);


            NotificationChannel callsChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_CALLING,
                    NOTIFICATION_CHANNEL_NAME_CALLING, NotificationManager.IMPORTANCE_HIGH);

            callsChannel.setSound(null, null);

            getManager().createNotificationChannel(callsChannel);


            NotificationChannel incomingCallsChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_INCOMING_CALLS,
                    NOTIFICATION_CHANNEL_NAME_INCOMING_CALLS, NotificationManager.IMPORTANCE_HIGH);

            incomingCallsChannel.setSound(null, null);

            getManager().createNotificationChannel(incomingCallsChannel);

            NotificationChannel backupChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_BACKUP,
                    NOTIFICATION_CHANNEL_NAME_BACKUP, NotificationManager.IMPORTANCE_HIGH);

            backupChannel.setSound(null, null);

            getManager().createNotificationChannel(backupChannel);


            NotificationChannel restoreChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_RESTORE,
                    NOTIFICATION_CHANNEL_NAME_RESTORE, NotificationManager.IMPORTANCE_HIGH);

            restoreChannel.setSound(null, null);

            getManager().createNotificationChannel(restoreChannel);



        }
    }

    private long[] getVibrationPattern() {
        return SharedPreferencesManager.isVibrateEnabled() ? new long[]{200, 200} : new long[0];
    }


    //get summary text (30 messages from 2 chats for example)
    private String getSubText(int messagesCount, int chatsCount) {
        String chats = chatsCount == 1 ? " Chat" : " Chats";
        String messages = messagesCount == 1 ? " Message" : " Messages";
        if (chatsCount <= 1) {
            return messagesCount + " New " + messages;
        }
        return messagesCount + messages + " from " + chatsCount + chats;
    }

    private String getUserNameWithNumOfMessages(int unreadCount,
                                                String userName) {
        if (unreadCount == 0 || unreadCount == 1)
            return userName;

        return userName + " " + "(" + unreadCount + " Messages" + ")" + " ";

    }

    public static boolean isBelowApi24() {
        return Build.VERSION.SDK_INT < 24;
    }


    private Bitmap getProfilePhotoAsBitmap(String thumbImg) {
        if (thumbImg != null)
            return BitmapUtils.encodeImage(thumbImg);

        
        
        return BitmapUtils.getBitmapFromVectorDrawable(this, R.drawable.user_img);

    }

    private String getSenderName(String userName, String groupName) {

        if (isBelowApi24() && groupName != null) {
            return userName + " @ " + groupName;
        }


        return userName;
    }

    
    public void dismissNotification(String chatId, boolean decrementCount) {

        Chat chat = RealmHelper.getInstance().getChat(chatId);
        if (chat != null) {

            int notificationId = isBelowApi24() ? ID_NOTIFICATION : chat.getNotificationId();
            getManager().cancel(notificationId);
            if (decrementCount) {
                updateNotificationCount(0);
                RealmHelper.getInstance().deleteUnReadMessages(chatId);
            }
            
            if (!isBelowApi24() && !RealmHelper.getInstance().areThereUnreadChats()) {
                
                getManager().cancel(ID_GROUP_NOTIFICATION);
            }
        }
    }

    //update Notification Count badge (in launcher)
    public void updateNotificationCount(int messagesCount) {

        if (messagesCount >= 0) {
            ShortcutBadger.applyCount(this, messagesCount);
        }
    }


    public void fireNotification(String newMessageChatId) {
        boolean isNotificationsEnabled = SharedPreferencesManager.isNotificationEnabled();
        long unreadMessagesCount = RealmHelper.getInstance().getUnreadMessagesCount();
if (isBelowApi24()) {
            
            HashMap<String, Chat> chatHashMap = new HashMap<>();
            
            List<Message> last7UnreadMessages = RealmHelper.getInstance().getLast7UnreadMessages();
            final NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle("");
            
            int chatsCount = (int) RealmHelper.getInstance().getUnreadChatsCount();
            String lastMessageTimestamp;

            Chat lastChat;

            
            if (last7UnreadMessages.isEmpty()) {
                getManager().cancel(ID_NOTIFICATION);
            } else {

                for (int i = 0; i < last7UnreadMessages.size(); i++) {

                    Message unreadMessage = last7UnreadMessages.get(i);

                    String chatId = unreadMessage.getChatId();
                    Chat chat;
                    
                    if (chatHashMap.containsKey(chatId)) {
                        chat = chatHashMap.get(chatId);
                        
                    } else {
                        chat = RealmHelper.getInstance().getChat(chatId);
                        chatHashMap.put(chatId, chat);
                    }

                    lastChat = chat;

                    lastMessageTimestamp = unreadMessage.getTimestamp();

                    
                   
                    if (isNotificationsEnabled && !chat.isMuted()) {
                        String sender = "";
                        if (chat.getUser().isGroupBool()) {
                            RealmList<User> users = chat.getUser().getGroup().getUsers();
                            User user = ListUtil.getUserById(unreadMessage.getFromId(), users);
                            if (user != null) {
                                sender = getSenderName(user.getProperUserName(), chat.getUser().getProperUserName());
                            }
                        } else {
                            if (chatsCount > 1)
                                sender = getSenderName(chat.getUser().getProperUserName(), null);
                        }

                        messagingStyle.addMessage(getMessageContent(unreadMessage, true), Long.parseLong(unreadMessage.getTimestamp()), sender);

                    }


                    NotificationCompat.Builder notificationBuilder =
                            createNotificationBuilder(
                                    ""
                                    , ""
                                    , chat, chatsCount);


                    if (chatHashMap.size() > 1) {
                        String appName = this.getResources().getString(R.string.app_name);
                        messagingStyle.setConversationTitle(appName);
                        notificationBuilder.setContentIntent(getPendingIntent(null));

                    } else {
                        messagingStyle.setConversationTitle(lastChat.getUser().getProperUserName());
                        notificationBuilder.setContentIntent(getPendingIntent(lastChat));
                    }


                    notificationBuilder.setSubText(getSubText((int) unreadMessagesCount, chatsCount));


                    notificationBuilder.setStyle(messagingStyle);

                    //set the timestamp of the last message
                    if (!lastMessageTimestamp.equals(""))
                        notificationBuilder.setWhen(Long.parseLong(lastMessageTimestamp));


                    //notify once after filling the messages
                    if (i == last7UnreadMessages.size() - 1)
                        getManager().notify(ID_NOTIFICATION, notificationBuilder.build());
                }
            }

            updateNotificationCount((int) unreadMessagesCount);

            //api24+ (grouping feature)
        } else {

            List<Chat> unreadChats = RealmHelper.getInstance().getUnreadChats();

            for (Chat unreadChat : unreadChats) {

                final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
                final NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle("");

                if (isNotificationsEnabled && !unreadChat.isMuted()) {


                    String userNameWithNumOfMessages = getUserNameWithNumOfMessages(unreadChat.getUnReadCount(), unreadChat.getUser().getProperUserName());

                    messagingStyle.setConversationTitle(userNameWithNumOfMessages);


                    //if it's a group or it's below api24 we will use messaging style
                    boolean isGroup = unreadChat.getUser().isGroupBool();

                    List<Message> messageList = RealmHelper.getInstance().filterUnreadMessages(unreadChat.getUnreadMessages());
                    if (isGroup) {
                        RealmList<User> users = unreadChat.getUser().getGroup().getUsers();

                        for (Message unreadMessage : messageList) {
                            User user = ListUtil.getUserById(unreadMessage.getFromId(), users);
                            if (user != null) {
                                String sender = getSenderName(user.getProperUserName(), unreadChat.getUser().getProperUserName());
                                messagingStyle.addMessage(getMessageContent(unreadMessage, true), Long.parseLong(unreadMessage.getTimestamp()), sender);
                            }
                        }
                    } else {
                        for (Message unreadMessage : messageList) {
                            inboxStyle.addLine(getMessageContent(unreadMessage, true));
                        }
                    }


                    NotificationCompat.Builder notificationBuilder =
                            createNotificationBuilder(
                                    userNameWithNumOfMessages
                                    , getMessageContent(unreadChat.getUnreadMessages().last(), true)
                                    , unreadChat, unreadChats.size());

                    //if it's a group we will use messaging style,otherwise we will user inboxStyle
                    notificationBuilder.setStyle(isGroup || isBelowApi24() ? messagingStyle : inboxStyle);

                    if (!unreadChat.getLastMessageTimestamp().equals(""))
                        notificationBuilder.setWhen(Long.parseLong(unreadChat.getLastMessageTimestamp()));


                    NotificationCompat.Builder groupNotification;

                    PendingIntent pendingIntent = getPendingIntent(unreadChat);
                    notificationBuilder.setContentIntent(pendingIntent);

                    
                    notificationBuilder.setOnlyAlertOnce(newMessageChatId.equals(unreadChat.getChatId()) ? false : true);


                    int notificationId = unreadChat.getNotificationId();
                    //group multiple notification in one grouped notification
                    groupNotification = createNotificationBuilder("", "", null, unreadChats.size());

                    if (!unreadChat.getLastMessageTimestamp().equals(""))
                        groupNotification.setWhen(Long.parseLong(unreadChat.getLastMessageTimestamp()));


                    //group notification by user id
                    groupNotification.setGroupSummary(true).setGroup(KEY_NOTIFICATION_GROUP);

                    
                    groupNotification.setOnlyAlertOnce(true);

                    groupNotification.setContentTitle("");

                    //set Summary (eg. 10 Messages from 3 Chat)
                    String subText = getSubText((int) unreadMessagesCount, unreadChats.size());

                    groupNotification.setSubText(subText);

                    notificationBuilder.setGroup(KEY_NOTIFICATION_GROUP);


                    notificationBuilder.addAction(getReplyActionInput(unreadChat));
                    notificationBuilder.addAction(getMarkAsReadAction(unreadChat));


                    getManager().notify(notificationId, notificationBuilder.build());
                    getManager().notify(ID_GROUP_NOTIFICATION, groupNotification.build());

                }
            }
            updateNotificationCount((int) unreadMessagesCount);
        }

    }


    //get onClick intent
    private PendingIntent getPendingIntent(Chat chat) {
        PendingIntent pendingIntent;
        if (isBelowApi24()) {
            //if it's only from one user then open the chatActivity with this user
            if (chat != null) {
                Intent intent = new Intent(this, ChatActivity.class);
                intent.putExtra(IntentUtils.UID, chat.getChatId());
                //adding stack for user (to prevent kill the app when click back since there is no previous activity launched
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                stackBuilder.addNextIntentWithParentStack(intent);
                pendingIntent = stackBuilder.getPendingIntent(ID_NOTIFICATION, PendingIntent.FLAG_UPDATE_CURRENT);
            } else {
                
                Intent intent = new Intent(this, MainActivity.class);
                pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            }

        } else {

            Intent intent = new Intent(this, ChatActivity.class);
            intent.putExtra(IntentUtils.UID, chat.getChatId());
            
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addNextIntentWithParentStack(intent);
            pendingIntent = stackBuilder.getPendingIntent(chat.getNotificationId(), PendingIntent.FLAG_UPDATE_CURRENT);
        }
        return pendingIntent;
    }

    private NotificationCompat.Builder createNotificationBuilder(
            String title, String message, Chat chat, int chatsCount) {


        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID_MESSAGES)
                //set app icon
                .setSmallIcon(R.drawable.ic_noti_icon)
                .setContentTitle(title)
                .setContentText(message)
                //color
                .setColor(ContextCompat.getColor(this, R.color.colorPrimary))
                .setDefaults(NotificationCompat.DEFAULT_LIGHTS)
                //Notification Sound (get it from shared preferences)
                .setSound(SharedPreferencesManager.getRingtone())
                //high priority to make it show as heads-up
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                //set vibrate if it's enabled by the user
                .setVibrate(getVibrationPattern());

        if (chat != null) {
            User user = chat.getUser();
            Bitmap largeIcon = getProfilePhotoAsBitmap(user.getThumbImg());

            if (!isBelowApi24() || chatsCount == 1)
                builder.setLargeIcon(largeIcon);

        } else {
            Bitmap largeIcon = getProfilePhotoAsBitmap(null);
            builder.setLargeIcon(largeIcon);
        }


        return builder;
    }

    private NotificationManager getManager() {
        if (manager == null) {
            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return manager;
    }

    

    
    


app is open Notification is showing but app is in the background Notification is not showing

0 Answers
Related