Updating android app widget manually using a button on the widget

iitum studant picture iitum studant · Oct 25, 2014 · Viewed 7.8k times · Source

I have a Android App widget and a button on the widget. I have set the update time period to 30mins but I also want to update the widget whenever I touch the button. here's my code:

        RemoteViews remoteV = new RemoteViews(context.getPackageName(), R.layout.widgetmenu);

        Intent intentSync = new Intent(context, MessMenuWidgetProvider.class);
        PendingIntent pendingSync = PendingIntent.getBroadcast(context,0, intentSync,0);
        remoteV.setOnClickPendingIntent(R.id.imageButtonSync,pendingSync);

        appWidgetManager.updateAppWidget(awID, remoteV);

I have set the update time to 30 mins so in every 30mins the function onUpdate() is called. What I want to achieve is to call onUpdate() manually using the button. But it's not happening. Any help?

Answer

Seth picture Seth · Oct 26, 2014

This is extremely easy. Below is the modified code to make the "onUpdate" method of your widget called each time the button is clicked.

RemoteViews remoteV = new RemoteViews(context.getPackageName(), R.layout.widgetmenu);

Intent intentSync = new Intent(context, MessMenuWidgetProvider.class);
intentSync.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); //You need to specify the action for the intent. Right now that intent is doing nothing for there is no action to be broadcasted.
PendingIntent pendingSync = PendingIntent.getBroadcast(context,0, intentSync, PendingIntent.FLAG_UPDATE_CURRENT); //You need to specify a proper flag for the intent. Or else the intent will become deleted.
remoteV.setOnClickPendingIntent(R.id.imageButtonSync,pendingSync);

appWidgetManager.updateAppWidget(awID, remoteV);

Now each time you click that button, the broadcast AppWidgetManager.ACTION_APPWIDGET_UPDATE will be sent to your widget and the method you have inside that class will handle the update. So either the onUpdate method is called, or the onReceive method is called. Whichever you have specified.