tdramble
tdramble

Reputation: 101

c2dm to update an android widget

I am in the planning stages for my next Android project. I would like to create widget for my current garage door opener app. Currently it is just an app and there is a refresh button at the bottom that updates the status of the door (open or closed). I would like for the network connected device in my garage to send a c2dm "push" message any time the status of my door changes so that I can do away with the refresh button all together. If I create a home screen widget that shows the status of the door, will it be able to update in real-time as these c2dm messages come in, or can widgets only be updated on a timer?

Upvotes: 1

Views: 399

Answers (1)

Patrick Jackson
Patrick Jackson

Reputation: 19446

Yes, You can have your widget updated as the C2DM(now GCM) come in.

Once your app receives the C2DM(or GCM) message you will either have to get your update from your server, or retrieve it from the message if you are sending it as payload with the message, and store it locally. Then you will have to start the update service for your widget, which you probably already are using. It is difficult to say exactly how to implement this without knowing more about your app. Generally the widget will have a service that updates. Below is a generic update service:

public static class UpdateService extends Service {
    @Override
    public void onStart(Intent intent, int startId) {
        RemoteViews updateViews = buildUpdate(this);

        // Push update for this widget to the home screen
        ComponentName thisWidget = new ComponentName(this, Widget.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        manager.updateAppWidget(thisWidget, updateViews);
    }


    public RemoteViews buildUpdate(Context context) {
       // process the updated view here.  Probably would pull data from DB and update views       //accordingly
        return updateViews;
    }


}

Upvotes: 1

Related Questions