Reputation: 3407
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);
Upvotes: 6
Views: 10188
Reputation: 15573
I wanted to change the widget background on button click, I used @2Dee 's answer. It didn't work for me until I updated the Widget after these changes:
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget2x2);
remoteViews.setInt(R.id.widget_layout2x2, "setBackgroundResource", R.drawable.border_radius);
//Don't forget to update the widget
AppWidgetManager mgr = AppWidgetManager.getInstance(context);
ComponentName me = new ComponentName(context, Widget2x2.class);
mgr.updateAppWidget(me, remoteViews);
Upvotes: 2
Reputation: 8629
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...
Upvotes: 18