Last updated on January 8th, 2020 at 10:08 pm

Broadcast Receiver is very useful when we can create a android application. It is very light a consume less system resource. In this post i explain you how we can pass data to current activity without relaunching it through broadcast receiver. This is very easy to understand and implement in your app. I use this technique in some of my chat application where i show incoming message to user without showing notification and refreshing its current chat activity screen.

Code

Step 1. Open your project where you want to implement this.

Step 2. Open your BroadcastReceiver class from where you pass data to activity inside your onReceive() you need to start intent and pass data inside intent and start sendBroadcast()  as shown bellow.

@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.e("Broadcast", "__________GCM Broadcast");
		
                Bundle extras = intent.getExtras();
                Intent i = new Intent("broadCastName");
                // Data you need to pass to activity
                i.putExtra("message", extras.getString(Config.MESSAGE_KEY)); 

                context.sendBroadcast(i);
	}

Step 3. Now register the receiver in activity where we get data.

Note. your activity need to be open to receive this data.

// Inside OnCreate Method
registerReceiver(broadcastReceiver, new IntentFilter("broadCastName"));


// Add this inside your class
BroadcastReceiver broadcastReceiver =  new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            Bundle b = intent.getExtras();

            String message = b.getString("message");

            Log.e("newmesage", "" + message);
        }
    };

That’s all. Hope this help you.

🙂