Receiving notifications within an activity

2

I can send a Firebase notification to my App but when I open that same notification it does not open within the Activity I want. How do I direct this notification to the activity so that I can see the message sent from Firebase?

    
asked by anonymous 07.12.2017 / 13:44

1 answer

0

First you have to go to your AndroidManifest.xml and add an action to your activity. Example:

  <activity android:name=".ActivityPrincipal">
            <intent-filter>
                <action android:name="ActivityPrincipal" />
            </intent-filter>

Within your class responsible for the firebase message service:

public void onMessageReceived(RemoteMessage remoteMessage) {

        Map<String,String> data = remoteMessage.getData();
        final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);

        if(remoteMessage.getNotification() != null)
        {

            Intent intent = new Intent("Notificacao");
            intent.putExtra("img",data.get("imagem"));
            System.out.println("IMAGEM:"+data.get("imagem"));
            broadcastManager.sendBroadcast(intent);
        }
        super.onMessageReceived(remoteMessage);
    }

In this case, I'm linking to an image by notification.

Within the Activity you want to open the message:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_principal);

        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver,
                new IntentFilter("Notificacao"));


    }

 private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            System.out.println("RECEBE!!!!");
            ImageView img = (ImageView)findViewById(R.id.imgview);
                Bundle dados  =intent.getExtras();
            String url = "http://192.168.0.12/img/"+dados.getString("img");
            System.out.println(url);
            Picasso.with(getBaseContext()).load(url).into(img);
            TextView txtmsg = (TextView)findViewById(R.id.textViewmensagem);
            TextView txttitulo = (TextView)findViewById(R.id.textViewtitulo);



            txtmsg.setText(dados.getString("mensagem"));
            txttitulo.setText(dados.getString("titulo"));
        }
    };

Within BroadcastReceiver, you do what needs to be shown.

Last step is to send the notification through the firebase, informing which activity has to be opened when clicking on the notification (in our case, the ActivityPrincipal)

Now in the api of firebase, you have to put this parameter:

click_action = "ActivityPrincipal"
    
07.12.2017 / 14:37