Mulgard
Mulgard

Reputation: 10589

Update running Activity using IntentService

I am using GCM-Notifications which are working really great! In my IntentService for the GCM-Notifications i use the following Code to create a notification:

/**
 * 
 */
private void sendMessagesUpdatedNotification() {
    Intent resultIntent = new Intent(this, MessageActivity.class);
    resultIntent.putExtra(Globals.KEY_UPDATED, true);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT);

    String title = this.getResources().getString(R.string.text_messages_updated);
    String message = this.getResources().getString(R.string.text_messages_updated_message);

    NotificationCompat.Builder builder = this.buildNotification(title, message);
    NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    builder.setSmallIcon(R.drawable.notification_ic_message);
    builder.setContentIntent(resultPendingIntent);
    builder.setAutoCancel(true);

    notificationManager.notify(MESSAGES_UPDATED_ID, builder.build());
}

If i click on the Notification my Activity gets started (or reloaded if shes already running). Everything great. Except one thing:

I want to have another feature. If my Activity is already in the front i want my content to be updated automatically without having to click on the notification.

Is that somehow possible?

Upvotes: 0

Views: 244

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006614

Is that somehow possible?

Use an event bus.

The service posts an event to the bus saying "hey, we got a message!". Your activity, while in the foreground, would be registered on the bus to receive events. If it gets the event, it updates the UI. If, however, the activity is not in the foreground, there are recipes for event bus implementations that would let your service know that the activity did not respond, and so you can raise the Notification as a fallback mechanism.

There are three major event bus implementations that I know of:

The sample apps are all the same core app, just using different event bus implementations. I used AlarmManager to trigger the service rather than a GCM message, but the same concept applies in your case with GCM.

Personally, I like greenrobot's EventBus for the more-flexible threading options, but all three can work in your case.

Upvotes: 2

Related Questions