notification push android do something when it arrives push closed app

12

I have in my app configured push notifications with firebase, all right here, I receive notifications with the app turned on and off, when it is open and something arrives I ask for the body to do certain actions for example to open another activity such as next example

 public class MiFirebaseMessagingService extends FirebaseMessagingService {

    public static final String TAG = "NOTICIAS";

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

        String from = remoteMessage.getFrom();
        Log.d(TAG, "Mensaje recibido de: " + from);

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Notificación: " + remoteMessage.getNotification().getBody());

            mostrarNotificacion(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Data: " + remoteMessage.getData());
        }

    }

    private void mostrarNotificacion(String title, String body) {

        Intent intent = null;
        if(body.equals("Login")){
            intent = new Intent(this, Login.class);
        }
        if(body.equals("AppIntro")){
            intent = new Intent(this, AppIntroGalery.class);

        }
        if(body.equals("Menu")){
            intent = new Intent(this, TabsActivity.class);
        }

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setSound(soundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());

    } }

What if I do not know how it could be achieved is for when it is closed this code seems not to work only opens it but does not go to the different activities any idea?

Try to put a flag to the intent

intent = new Intent(this, SplashInicio.class);
    intent.putExtra("idScreen", 12);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

splash class:

 @Override
protected void onNewIntent(Intent intent) {


    String idScreen = getIntent().getExtras().getString("idScreen");
    if(idScreen.equals("12")){
        startActivity(new Intent(this, Login.class));

    }

    // clean intent for new Push Notification Data.
    super.onNewIntent(null);
}

also without results, to be more specific I need that when the app is closed and I get notifications, it depends on what I got in the message to make a certain action the best would be to open an activity and send a flag or not

I add Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="odontosys.com.odontosys">
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/pagoexitosoxxxhdpi"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/audi"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <service

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

    </service>

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

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/ic_launcher_round" />

    <activity android:name=".SplashInicio"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>
    <activity android:name=".Login"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateHidden">
        <intent-filter>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


    <activity android:name=".ListadoClientes"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateHidden">
    </activity>

    <activity android:name=".AppIntroGalery"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateHidden">
    </activity>


    <activity
        android:name=".TabsActivity"
        android:label="@string/title_activity_tabs"
        android:theme="@style/AppTheme.NoActionBar">

    </activity>


</application>

    
asked by Bruno Sosa Fast Tag 30.03.2018 в 19:41
source

3 answers

5

Bruno, the reception of data in your class that extends from FirebaseMessagingService and that specifically occurs in onMessageReceived() is understood to be to generate a notification, this does not matter if the application is open or closed.

As for your method this can work without any problem, you do NOT need to specify any type of FLAG or use onNewIntent () :

   private void mostrarNotificacion(String title, String body) {

        Intent intent = null;
        if(body.equals("Login")){
            intent = new Intent(this, Login.class);
        }
        if(body.equals("AppIntro")){
            intent = new Intent(this, AppIntroGalery.class);

        }
        if(body.equals("Menu")){
            intent = new Intent(this, TabsActivity.class);
        }

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setSound(soundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());

    }

To work properly you have to take these points into account:

1) You need to specify your activities within your AndroidManifest.xml file

 ...  
        <activity android:name=".Login"/>
        <activity android:name=".AppIntroGalery"/>
        <activity android:name=".TabsActivity"/>
    </application>

...

2) The body parameter must specifically contain the text you indicate in the comparison:

   if(body.equals("Login")){
   ...
   if(body.equals("AppIntro")){
   ...
   if(body.equals("Menu")){
   ...

3) the most important point is that using FCM is received in RemoteMessage and not a Bundle. You are showing the notification if remoteMessage.getNotification() :

   if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Notificación: " + remoteMessage.getNotification().getBody());

            mostrarNotificacion(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }

but does not open the intent to the Activity because the value of remoteMessage.getNotification().getBody() , is not "Login", "AppIntro" or "Menu", you should check this point.

It is also important to change the code of the notification because if you received a previously that did not have body with the same code that you have with value 0, then this would cause you not to open any Activity, I suggest you create a method to obtain a random value that will serve as a code:

private int getRandomCode(){
    //Obtiene un valor entre 1000.
    Random rand = new Random();
    return rand.nextInt(1000 - 0 + 1);
}

and define this code in the intent:

 private void mostrarNotificacion(String title, String body) {

        int codigo = getRandomCode();

        Intent intent = null;
        if(body.equals("Login")){
            intent = new Intent(this, Login.class);
        }
        if(body.equals("AppIntro")){
            intent = new Intent(this, AppIntroGalery.class);

        }
        if(body.equals("Menu")){
            intent = new Intent(this, TabsActivity.class);
        }

       // intent = new Intent(this, TabsActivity.class);
        intent.putExtra("idScreen", 12);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, codigo/*0*/, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setSound(soundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(codigo /*0*/, notificationBuilder.build());

 }

In this case only the first notification will open a Activity in the application because as I commented the condition is that body has a value of "Login", "AppIntro" or "Menu", if you open some that do not fulfill this condition, it will be opened simply from the beginning.

    
answered by 30.03.2018 / 23:50
source
3

I tell you that if you have the app closed it will not work that way, because I already tried, what the firebase documentation recommends and if it works, it is to send in the data of the message, the activity that I am looking for open when you click on the notification and of course, the background color so that the icon does not look all white, I send it from php in this way, but it would apply for any other way of requesting it:

$msg = array(
                'title'        => 'miTitulo',
                'body'         => 'miAsunto',
                'icon'         => 'ic_notifi_icon',
                'sound'        => 'defaultSoundUri',
                'click_action' => 'miActivity',//Actividad que se abrirá al momento de hacer clic en la notificacion
                'color'        => '#3F51B5'
            );

$fields = array(
                    'to'=> '/topics/'.$this->topic, 
                    'notification'  => $msg
                );

$headers = array(
                    'Authorization: key=' . $this->apikey, 
                    'Content-Type: application/json'
                );


$ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );

The subject in question is click_action , which is where you indicate which activity you want to open by clicking on the notification. The color Serves when the icon goes blank, because when it is in the background or closed, it does not take the configuration of the firebase listener.

This works perfect when the app is closed or in the background.

  

REPOSITORY with php form for sending push notifications

Greetings

    
answered by 31.03.2018 в 03:50
3

Well one of the ways to do what you want is to get the data from the main activity that is the first to open. When the app is completely closed and you get a notification when you click on the notification, it will open the main intent with data like Extras, then those extras should be obtained in the following way in your onResume

@Override
protected void onResume() {
    if(getIntent().getExtras() != null) {

        Bundle b = getIntent().getExtras();

        try {
            String actionType = b.getString("action");
            //aquí va tu código en el cual validas el tipo de dato
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Now you will ask for example because it sends to get action , well as I asked you if you were using the Firebase console in the Custom data section you can put action as the Key and then the values would be the ones you want to review Login AppIntro etc. This answer goes more to based on my experience when receiving Push notification in FireBase With the App closed and make an action according to the received in the notification.

As an annex to my answer, I sent you the link on how to send the data when using FCM: Receive Messages

    
answered by 03.04.2018 в 20:39