Vigneshwaran T Vigneshwaran T - 1 month ago 18
Android Question

Broadcast Receiver is not receiveing the intent data in android.Looking for Solution

I am trying to send intent data to

MainActivity
.And i'm receiving the data from
GCM Server
, that received data I want to send to my
MainActivity
.

In GcmBroadcastReceiver Class

ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);

Bundle extras = intent.getExtras();
Intent i = new Intent("CHAT_MESSAGE_RECEIVED");
i.putExtra("Message", extras.getString("Message"));
i.putExtra("Sender",extras.getString("Sender"));
i.putExtra("Receiver",extras.getString("Receiver"));
i.putExtra("Calltype",extras.getString("calltype"));
context.sendBroadcast(i);


These above code I am using to receive the data from
GCM Sever
and also use the
BroadcastReceiver
to send data.

In MainActivity Class

registerReceiver(broadcastReceiver,newIntentFilter("CHAT_MESSAGE_RECEIVED"));
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
String message = b.getString("Message");
String sender=b.getString("Sender");
String receiver=b.getString("Receiver");
}
};


In activity I have used the broadcast receiver to receive the intent with data.

Answer
In your GcmListenerService # onMessageRecieved() function use this code
 Intent intent = new Intent(ANY_TAG);
        sendBroadcast(intent);

AND in your activity use following code

 private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            displayToast(" Data received");
        }
    };

 @Override
    public void onResume() {
        super.onResume();
        getContext().registerReceiver(mMessageReceiver, new IntentFilter(ANY_TAG));
    }

    @Override
    public void onPause() {
        super.onPause();
        getContext().unregisterReceiver(mMessageReceiver);
    }