Widget setOnClickPendingIntent

android

Solution

You can use `PendingIntent.getBroadcast` which will be received in your `AppWidgetProvider` class :

Intent intent = new Intent(context, YourAppWidgetProvider.class);
intent.setAction("use_custom_class");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.imageViewWidgetToggle, pendingIntent);

and then in the `AppWidgetProvider` :

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    String action = intent.getAction();
    String actionName = "use_custom_class";

    if (actionName.equals(action)) {
        MyClass mc = new MyClass(context);
        mc.toggleEnable();
    }
}

Have a look at the docs about PendingIntent for details on the flags to use. I hope I understood your question correctly and that my answer made sense to you :) If not, don't hesitate to let me know...

Problem

So, I am having a hard time figuring out how to make my app widget work the way I want it to, or if its even possible. The Widget has a `ImageView` and I assign a `setOnClickPendingIntent` to it. However, what I want to accomplish is basically just to instantiate a class and call a method in that class when the user taps the `ImageView` in the app widget. However, how can I make the `PendingIntent` do something else than just firing up an activity instead? Not sure if this made any sense, but I really appreciate the help. ``` // Create an Intent to launch MainActivity Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); /** /* However, I want to simply do something like this /* MyClass mc = new MyClass(context); /* mc.toggleEnable(); */ // Get the layout for the App Widget and attach an on-click listener // to the button RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); views.setOnClickPendingIntent(R.id.imageViewWidgetToggle, pendingIntent); ```

Original source