0

Tengo una app android que recibe notificaciones push con firebase, las notificaciones son normales en la barra de estado, lo que me interesa es saber como generar notificaciones emergentes, osea que al enviar las notificaciones desde firebase a mi aplicación, me genere automaticamente una notificación emergente o flotante. Lo que he logrado hasta el momemto es que me genere las notificaciones flotantes pero solo cuando la aplicacion está en uso, cuando cierro la aplicación las notificaciones me caen normalmente. ¿Alguna idea? se los agradecería mucho. `DEJO MI CODIGO ADJUNTO.

public class MyFirebaseMessagingService extends FirebaseMessagingService 
{

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // ...

    if(remoteMessage.getData().isEmpty())
        showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
    else showNotification(remoteMessage.getData());


    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
        } else {
            // Handle message within 10 seconds
        }

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}

public void showNotification(Map<String, String> data) {
    String title = data.get("title").toString();
    String body = data.get("body").toString();
    String NOTIFICATION_CHANNEL_ID = getString(R.string.default_notification_channel_id);
    //
    Intent fullScreenIntent = new Intent(this, MainActivity.class);
    fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
            fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_stat_ic_notification)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setAutoCancel(true)
                    .setContentIntent(fullScreenPendingIntent)
                    // Use a full-screen intent only for the highest-priority alerts where you
                    // have an associated activity that you would like to launch after the user
                    // interacts with the notification. Also, if your app targets Android 10
                    // or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
                    // order for the platform to invoke this notification.
                    .setFullScreenIntent(fullScreenPendingIntent, true)
                    .setWhen(System.currentTimeMillis());

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                "Notification",
                NotificationManager.IMPORTANCE_HIGH);

        notificationChannel.setDescription("Descripcion");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.BLUE);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableLights(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

private void showNotification(String title, String body) {
    Intent fullScreenIntent = new Intent(this, MainActivity.class);
    fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
            fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    String NOTIFICATION_CHANNEL_ID = getString(R.string.default_notification_channel_id);

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_stat_ic_notification)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setAutoCancel(true)
                    .setContentIntent(fullScreenPendingIntent)
                    // Use a full-screen intent only for the highest-priority alerts where you
                    // have an associated activity that you would like to launch after the user
                    // interacts with the notification. Also, if your app targets Android 10
                    // or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
                    // order for the platform to invoke this notification.
                    .setFullScreenIntent(fullScreenPendingIntent, true)
                    .setWhen(System.currentTimeMillis());

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                "Notification",
                NotificationManager.IMPORTANCE_HIGH);

        notificationChannel.setDescription("Descripcion");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.BLUE);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableLights(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}`

1

1 respuesta 1

0

Agrega esto a tu manifest

<meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id" />
1
  • 1
    Hola, gracias por el aporte. Estaría bueno si agregas una explicación de qué hace ese código, así podemos aprender y no sólo copiar y pegar algo que no sabemos cómo funciona. el 7 may. 2020 a las 13:31

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.