harisK92 harisK92 - 1 year ago 97
Android Question

Sending data from GCMIntentService and receiving it in main activity

Hi I want to send a data from GCMIntentService to mine main activity and I want to receive it there?How can I achieve it ?

Iam pretty stuck with that
In mine main activity I have list and I want to upadate it depending on received message.

public class GcmIntentService extends IntentService {

public GcmIntentService() {
public static final String TAG = "GCM Service";

protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);

if (!extras.isEmpty()) { // has effect of unparcelling Bundle
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendData("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendData("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
} catch (InterruptedException e) {
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendData("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
// Release the wake lock provided by the WakefulBroadcastReceiver.

private void sendData(String msg) {

//I want to send the data to main activity and Iam stuck here
//should I use sendBroadcast and broadcast receiver or something else ?

Answer Source

To do that you need first override the method on you activity onNewIntent and change the launch mode of your activity.



On you service

Intent intent = new Intent(context, YourActivityClass.class);

// This make the magic 

//add some data extra
intent.putExtra("data","from outside");


on you activity

protected void onNewIntent(Intent intent) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download