66

The developer documentation has seemed to have failed me here. I can create a static widget without thinking, I can even create a widget like the analogue clock widget that will update itself, however, I can not for the life of me figure out how to create a widget that reacts to when a user clicks on it. Here is the best code sample that the developer documentation gives to what a widget activity should contain (the only other hint being the API demos, which only creates a static widget):

public class ExampleAppWidgetProvider extends AppWidgetProvider {
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        // Perform this loop procedure for each App Widget that belongs to this provider
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            // Create an Intent to launch ExampleActivity
            Intent intent = new Intent(context, ExampleActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            // Get the layout for the App Widget and attach an on-click listener to the button
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
            views.setOnClickPendingIntent(R.id.button, pendingIntent);

            // Tell the AppWidgetManager to perform an update on the current App Widget
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}

from: The Android Developer Documentation's Widget Page

So, it looks like pending intent is called when the widget is clicked, which is based off of an intent (I'm not quite sure what the difference between an intent and a pending intent is), and the intent is for the ExampleActivity class. So I made my sample activity class a simple activity that when created, would create a mediaplayer object, and start it (it wouldn't ever release the object, so it would eventually crash, here is it's code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
    mp.start();
}

However, when I added the widget to the home screen, and clicked on it, nothing played, in fact, nothing played when I set the update timer to just a few hundred milliseconds (in the appwidget provider xml file). Furthermore, I set break points and found out that not only was it never reaching the activity, but no break points I set would ever get triggered. (I still haven't figured out why that is), however, logcat seemed to indicate that the activity class file was being run.

So, is there anything I can do to get an appwidget to respond to a click? As the onClickPendingIntent() method is the closest I have found to a onClick type of method.

1
  • Hai Leif, do you solve this problem by Brain515's Methode? I have a similar problem, But the Brain's solution not work for me, Can you please help me? Commented Jun 6, 2012 at 9:15

2 Answers 2

130

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!

10
  • 1
    where this line ( Intent intent = new Intent(context, ExampleActivity.class);) is place? What does the widget.class contain? I guess ExampleActivity is what we want to launch Commented Feb 1, 2012 at 19:51
  • 1
    Edited the reply to a method some extra steps that are needed for this to work. The getBroadcast is important for the PendingIntent to be broadcast, rather than getActivity from the example.
    – Guykun
    Commented Jun 20, 2012 at 10:26
  • 1
    .getActivity is used to open an activity e.g. when you click an object in the widget
    – erdomester
    Commented Oct 13, 2012 at 6:53
  • 1
    Use a LocalBroadcastManager instead of generic broadcasts Commented Jan 5, 2013 at 12:50
  • 1
    AFAIK there's no way to use PendingIntent with LocalBroadcastManager
    – vault
    Commented Apr 4, 2013 at 14:11
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.

1
  • Why do you do this for every widget update? Surely it just needs to be done once? Commented Jun 25, 2020 at 9:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.