从GCMIntentService发送数据并在主活动中接收它

时间:2014-06-13 14:01:57

标签: android google-cloud-messaging

您好我想从GCMIntentService发送一个数据来挖掘主要活动,我想在那里收到它?我怎样才能实现它?

我非常坚持这一点 在我的主要活动中,我有列表,我想根据收到的消息更新它。

public class GcmIntentService extends IntentService {


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

    @Override
    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 {
                    Thread.sleep(5000);
                } 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.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
    }


    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 ?
     }
}

1 个答案:

答案 0 :(得分:2)

为此,您需要首先覆盖活动onNewIntent上的方法并更改活动的启动模式。

的manifest.xml

android:launchMode="singleTop"

在您服务上

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

// This make the magic 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

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

getApplicationContext().startActivity(intent);

关于你的活动

@Override
protected void onNewIntent(Intent intent) {

}