How to receive notifications within an Activity

Asked

Viewed 235 times

1

I can send a notification from Firebase to my App but Open that same notification doesn’t open inside the Activity I want. How do I direct this notification to Activity so that I can see the message sent from Firebase?

1 answer

1


First you have to go in your Androidmanifest.xml and add an action to your Activity. Example:

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

Within its firebase message service class:

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,.

Inside 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"));
        }
    };

Inside the Broadcastreceiver, you do what needs to be shown.

Last step is to send the notification by firebase, stating which Activity has to be opened by clicking on the notification ( in our case,)

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

click_action = "ActivityPrincipal"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.