4

I'm trying to manage notifications, but I am not able to do nothing with them when app is in foreground.

When app is minimified or completly closed, the notification is correctly shown, but if app is in foreground it is not seen.

I have test variations of this code, but nothing works. The notifications with app closed or minimified works wit any modification of this code, or with any this code at all:

(EDITED following comments indications, same result)

import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import PACKAGE_NAME.ContenedorPrincipal
import PACKAGE_NAME.R
import PACKAGE_NAME.general.General
import java.text.SimpleDateFormat
import java.util.*
//import java.util.concurrent.atomic.AtomicInteger

class ServicioNotificaciones: FirebaseMessagingService()
{
    //private val c = AtomicInteger(0)

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)

        try{
            val uniqueID = Integer.parseInt(SimpleDateFormat("ddHHmmss",  Locale.getDefault()).format(Date()))

            val mNotificationManager: NotificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(
                    "notificationChannelID",
                    "notificationChannelName",
                    NotificationManager.IMPORTANCE_HIGH)

                mNotificationManager.createNotificationChannel(notificationChannel)
            }


            val mBuilder: NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, "notify_001")
            val ii = Intent(applicationContext, ContenedorPrincipal::class.java)
            val pendingIntent = PendingIntent.getActivity(applicationContext, 0, ii, 0)

            val bigText = NotificationCompat.BigTextStyle()
            bigText.bigText(remoteMessage.notification?.body ?: "")
            bigText.setBigContentTitle(remoteMessage.notification?.title ?: "")
            bigText.setSummaryText(remoteMessage.notification?.body ?: "")

            mBuilder.setContentIntent(pendingIntent)
            mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
            mBuilder.setContentTitle(remoteMessage.notification?.title ?: "")
            mBuilder.setContentText(remoteMessage.notification?.body ?: "")
            @Suppress("DEPRECATION")
            mBuilder.priority = Notification.PRIORITY_MAX
            mBuilder.setStyle(bigText)

            val buildedNotification = mBuilder.build()

            //mNotificationManager.notify(c.incrementAndGet(), buildedNotification)
            mNotificationManager.notify(uniqueID, buildedNotification)

            /*Looper.prepare()
            General.mostrarConfirmacion(
                remoteMessage.notification?.title ?: "",
                remoteMessage.notification?.body ?: "",
                AlertDialog.Builder(this)
            )*/
        }
        catch (ex: Exception){
            Log.wtf("onMessageReceivedEX", ex.message.toString())
        }
    }
}

And manifest:

   <service
            android:name="PACKAGE_NAME.servicios.ServicioNotificaciones"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
    </service>

EDIT 2: I finnaly make it work with this code:

                val intent2 = Intent(this, MainActivity::class.java)
            intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            val pendingintent2 = PendingIntent.getActivity(this, 0, intent2, PendingIntent.FLAG_ONE_SHOT)
            val channelId = "Default"
            val builder = NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(remoteMessage.notification?.title)
                .setContentText(remoteMessage.notification?.body).setAutoCancel(true)
                .setContentIntent(pendingintent2)
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(
                    channelId,
                    "Default channel",
                    NotificationManager.IMPORTANCE_DEFAULT
                )
                manager.createNotificationChannel(channel)
            }
            manager.notify(uniqueID, builder.build())

Thanks you all!

msolla
  • 306
  • 1
  • 3
  • 16

3 Answers3

2

You have to use notification channel:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val notificationChannel = NotificationChannel(
        "notify_001",
        getString(R.string.notification_channel_name),
        NotificationManager.IMPORTANCE_HIGH)

    mNotificationManager.createNotificationChannel(notificationChannel)
}
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
1

I Don't see where do you create the notification channel (Since Android O it is a must).

Create and Manage Notification Channels

Community
  • 1
  • 1
CmTiger
  • 74
  • 6
  • Ì didn't. But I added this by following your link steps and @Md. Asaduzzaman indications, but did'nt work for me. – msolla Oct 17 '19 at 11:51
0

i think this issue related to sent notification not to receive notification try to sent notification like this

"data": {
  "data_title": "test",
  "data_body" : "test"
 }
Moayed Alayaseh
  • 243
  • 7
  • 16
  • No, it didn't. The notification always was received, simply it was not shown in foreground. I finnally fix it. Thanks a lot! – msolla Oct 17 '19 at 14:38
  • @msolla can you please explain how did you fixed this – Saurabh Apr 24 '20 at 07:14
  • 1
    @Saurabh I edditted the original question with the fix that worked for me, look at EDIT 2 :) (forgiveness for slow to respond) – msolla Sep 02 '20 at 11:17