es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Las notificaciones FCM no se muestran en primer plano en Android.

Las notificaciones se muestran en segundo plano, pero cuando la aplicación está en primer plano las notificaciones no se muestran. He aplicado muchas soluciones, pero no funcionan para mí. ¿Alguien puede decirme dónde está mi error? Gracias de antemano.

Aquí está el Archivo Manifest:

     <service android:exported="false" android:name=".services.MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"></action>
    </intent-filter>
</service>

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/cute"></meta-data>
<meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/design_default_color_on_primary"></meta-data>

Aquí está la clase My Services:

const val cannelId = “notification_channel”
const val channel_name = “com.dextrologix.dham.rfms.resident.services”
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.notification != null) {

        genrateNotification(
            remoteMessage.notification!!.title!!,
            remoteMessage.notification!!.body!!
        )
    }
}
@SuppressLint("RemoteViewLayout")
fun getRemoteView(title: String, message: String): RemoteViews {
    val remteViews = RemoteViews(
        "com.dextrologix.dham.rfms.resident.services",
        R.layout.pushnotification_layout
    )
    remteViews.setTextViewText(R.id.notification_title, title)
    remteViews.setTextViewText(R.id.notification_message, message)
    remteViews.setImageViewResource(R.id.notification_image, R.drawable.cute)
    return remteViews
}
fun genrateNotification(title: String, message: String) {
    var intent = Intent(this, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
    var builder: NotificationCompat.Builder =
        NotificationCompat.Builder(applicationContext, cannelId)
            .setSmallIcon(R.drawable.person_icon)
            .setAutoCancel(true)
            .setVibrate(longArrayOf(1000, 1000, 1000, 1000))
            .setOnlyAlertOnce(true)
            .setContentIntent(pendingIntent)

    builder = builder.setContent(getRemoteView(title, message))
    val notificationManager =
        getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val notificationChannel =
            NotificationChannel(cannelId, channel_name, NotificationManager.IMPORTANCE_HIGH)
        notificationManager.createNotificationChannel(notificationChannel)
    }
    notificationManager.notify(0, builder.build())

}

}

Tags:  , , , ,

Answer

  1. Avatar for davy.ai

    Una de las razones de este problema puede ser que la aplicación no esté manejando correctamente las notificaciones cuando está en primer plano. Por defecto, FirebaseMessagingService no mostrará notificaciones cuando la aplicación esté en primer plano. En su lugar, activará el método onMessageReceived y le dará la oportunidad de manejar la notificación usted mismo.

    Para mostrar notificaciones en primer plano, debe llamar explícitamente al método NotificationManagerCompat.notify() con el ID de notificación y el creador de notificaciones que haya creado. Para hacer esto, puede modificar la función genrateNotification para verificar si la aplicación está en primer plano y llamar NotificationManagerCompat.notify() en consecuencia:

    fun genrateNotification(title: String, message: String) {
        ...
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    
        val isAppInForeground = isAppInForeground(this)
        if (isAppInForeground) {
            // La aplicación está en primer plano, muestra la notificación inmediatamente
            NotificationManagerCompat.from(this).notify(0, builder.build())
        } else {
            // La aplicación está en segundo plano, muestra la notificación en la bandeja de notificación
            notificationManager.notify(0, builder.build())
        }
    }
    
    fun isAppInForeground(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningTasks = activityManager.getRunningTasks(1)
        if (runningTasks.isNotEmpty()) {
            val topActivity = runningTasks[0].topActivity
            if (topActivity.packageName == context.packageName) {
                return true
            }
        }
        return false
    }
    

    Si esto no resuelve el problema, debe verificar que las notificaciones se estén enviando correctamente desde el servidor y que la aplicación las esté recibiendo. Puede hacer esto utilizando las herramientas de prueba de Firebase Cloud Messaging, o agregando declaraciones de registro a su clase MyFirebaseMessagingService para verificar que onMessageReceived se está activando correctamente.

Comments are closed.