2

A través de un Tutorial pude lanzar Notificaciones FCM para Android desde mi servidor.

Funciona perfectamente pero me encuentro con estas inquietudes para poder terminar el proyecto:

Actualmente cuando recibo la Notificación, la misma me envía al MainActivity (el cual levanta la web/App a través del webview y lo que yo necesito es "que directamente vaya a MainActivity2 (el cual levantaría otro webview con la página de Promociones de la Web.

Espero que me haya explicado bien y agradezco su colaboración.

Dejo el código:

AndroidManifest.xml:

    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity2"
        android:launchMode="singleTask"
        android:taskAffinity=""
        android:excludeFromRecents="true">
    </activity>

    <service android:name=".NotificacionesServicio">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

Notificaciones.java:

    private void enviarNotificacion(RemoteMessage remoteMessage) {
        Map<String, String> data = remoteMessage.getData();
        String title = data.get("title");
        String body = data.get("body");

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "GSdeveloper";

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Solo para android Oreo o superior
            @SuppressLint("WrongConstant")
            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
            "Mi notificacion",
            NotificationManager.IMPORTANCE_MAX
            );

            // Configuracion del canal de notificación
            channel.setDescription("Qué Comemos?");
            channel.enableLights(true);
            channel.setLightColor(Color.BLUE);
            channel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            channel.enableVibration(true);

            manager.createNotificationChannel(channel);

        }

        Intent intent = new Intent(this, MainActivity2.class);
        intent.putExtra("Mensaje", remoteMessage.getNotification().getBody());
        //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

        CharSequence link = null;
        PendingIntent notifyPendingIntent = null;
        builder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_stat_name_ic_notification)
                .setTicker("Qué Comemos?")
                .setContentTitle(title)
                .setContentText(body)
                .setVibrate(new long[]{0, 1000, 500, 1000})
                .setContentIntent(notifyPendingIntent)
                .setContentInfo("info");

            manager.notify(1, builder.build());
        }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        if (remoteMessage.getData() != null) {
            enviarNotificacion(remoteMessage);
        }
        if (remoteMessage.getNotification() != null) {
            String TAG = null;
            Log.d(TAG, "Body notification: " + remoteMessage.getNotification().getBody());
            enviarNotificacion(remoteMessage);

            
            Intent notifyIntent = new Intent(this, MainActivity2.class);
            // Set the Activity to start in a new, empty task
            notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            // Create the PendingIntent
            PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }



MainActivity2.java:

    public class MainActivity2 extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);

            WebView webView = this.findViewById(R.id.webviewdos);
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.startsWith("http:") || url.startsWith("https:")) {
                        return false;
                    }
                    // Habilita el StarActivity para  whatsapp, tel, mailto, etc.
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    //Desabilita el Atar Activity >> Intent intent = null;
                    startActivity(intent);
                    return true;
                }
            });


            webView.loadUrl("https://transporteelchanguito.com/app/producto.php?id=8");

            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
        }

        @Override
        public void onBackPressed(){
            WebView wv = (WebView)findViewById(R.id.webviewdos);
            if(wv.canGoBack()){
                wv.goBack();
            } else {
                super.onBackPressed();
            }
        }
    }

1 respuesta 1

1

Para poder abrir una actividad desde la notificación puedes usar addAction(icon, title, intent) en el código que ya tienes, el primer parámetro es el icono que quieres ponerle, el segundo es el texto que tendrá la opción y el ultimo es el intent que quieres abrir.

Te dejo el ejemplo con una porción de tu código:

Intent intent = new Intent(this, MainActivity2.class);
intent.putExtra("Mensaje", remoteMessage.getNotification().getBody());
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

CharSequence link = null;
PendingIntent notifyPendingIntent = null;
builder.setAutoCancel(true)

        // Aquí agregamos la acción
        .addAction(R.drawable.ic_icon, "Abrir actividad", pendingIntent)

        .setDefaults(Notification.DEFAULT_ALL)
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.drawable.ic_stat_name_ic_notification)
        .setTicker("Qué Comemos?")
        .setContentTitle(title)
        .setContentText(body)
        .setVibrate(new long[]{0, 1000, 500, 1000})
        .setContentIntent(notifyPendingIntent)
        .setContentInfo("info");

manager.notify(1, builder.build());

Aquí puedes encontrar la documentación para addAction.

Edición:

Puedes encontrar un ejemplo para versiones mayores del API 23 en éste enlace, ya que al parecer addAction(icon, title, intent) fue deprecado para API 23 y en su lugar solicitan utilizar addAction(action).

Ejemplo que se muestra en el enlace

 // Create the reply action and add the remote input.
 NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
               getString(R.string.label), replyPendingIntent)
               .addRemoteInput(remoteInput)
               .build();

 // Build the notification and add the action.
 Notification newMessageNotification = new Notification.Builder(context, CHANNEL_ID)
         .setSmallIcon(R.drawable.ic_message)
         .setContentTitle(getString(R.string.title))
         .setContentText(getString(R.string.content))
         .addAction(action)
         .build();

 // Issue the notification.
 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
 notificationManager.notify(notificationId, newMessageNotification);
9
  • Gracias Israel por tu colaboración! Te cuento que coloqué tu código y funciona pero me doy cuenta que cuando la App está cerrada no abre la Actividad2, me lleva a la App mostrando la Actividad principal (o sea, abre la App y queda ahí). el 18 ago. 2021 a las 1:58
  • Mmmm es extraño, yo uso ese código y me abre normal la actividad que necesito aunque la app este cerrada. Lo único que se me ocurre es que en el manifest agregues el intent-filter como <category android:name="android.intent.category.DEFAULT" /> para la actividad MainActivity2.
    – Israel-ICM
    el 18 ago. 2021 a las 12:36
  • No Israel, no tengo resultado tampoco con este category. Aprovecho para consultarte una más: el 18 ago. 2021 a las 14:06
  • Quiero capturar el put.Extra("Link") que envío en la NotificacionesServicio.java: Intent notifyIntent = new Intent(this, MainActivity2.class); notifyIntent.putExtra("link", remoteMessage.getNotification().getLink()); Bundle miBundle=new Bundle(); miBundle.putString("link", String.valueOf(remoteMessage.getNotification().getLink())); notifyIntent.putExtras(miBundle); Activity2: Intent notifyIntent = getIntent(); Bundle miBundle = this.getIntent().getExtras(); String link = miBundle.getString("link"); webView.loadUrl(link); // <--- Pero en todos los intentos el dato está vacío... el 18 ago. 2021 a las 14:28
  • Prueba con PendingIntent.FLAG_UPDATE_CURRENT al usar el PendingIntent, algo así: PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    – Israel-ICM
    el 18 ago. 2021 a las 14:34

Tu Respuesta

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

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