Clickable widgets in android
Solution 1:
First, add a static variable with a constant.
public static String YOUR_AWESOME_ACTION = "YourAwesomeAction";
Then you need to add the action to the intent before you add the intent to the pending intent:
Intent intent = new Intent(context, widget.class);
intent.setAction(YOUR_AWESOME_ACTION);
(Where widget.class is the class of your AppWidgetProvider, your current class)
You then need to create a PendingIntent with getBroadcast
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
Set the onClickPendingIntent for the clickable view in your widget
remoteView.setOnClickPendingIntent(R.id.widgetFrameLayout, pendingIntent);
Next, override the onReceive method in the same class:
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
And then respond to your button presses by querying the intent returned for your action within the onReceive method:
if (intent.getAction().equals(YOUR_AWESOME_ACTION)) {
//do some really cool stuff here
}
And that should do it!
Solution 2:
Leave the onUpdate method as it was and copy-paste the logic to updateAppWidget.
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
// Create an Intent to launch ExampleActivity when clicked
Intent intent = new Intent(context, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
// Widgets allow click handlers to only launch pending intents
views.setOnClickPendingIntent(R.id.button, pendingIntent);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
PS. PendingIntent is just "box" for an Intent, that allows other applications to have access and run that Intent in your application.