Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
AppWidgetProvider for configurable widget, onUpdate example
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
WidgetEntryDao dao = new WidgetEntryDao(new DbHelper(context));
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];
// Finding the widget entry for the app widget id
WidgetEntry entry = dao.findByWidgetId(appWidgetId);
if (entry != null) {
// creating the intent with all the information we want to pre-fill
Intent intent = new Intent(Intent.ACTION_SEND);
// array of destination email addresses
intent.putExtra(Intent.EXTRA_EMAIL, entry.getTo());
// subject (optional)
intent.putExtra(Intent.EXTRA_SUBJECT, entry.getSubjectPrefix());
// little bonus, we're adding some kind of signature after the (optional) message
intent.putExtra(Intent.EXTRA_TEXT, entry.getMessagePrefix() + "\n\n\n" + context.getString(R.string.signature));
// and setting a type that will narrow the choice of apps that handle email related stuff
// creating pending intent, the flag is REALLY importat, and so is the appWidgetId
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
// using main layout to handle the click, so the whole widget is a button
views.setOnClickPendingIntent(, pendingIntent);
// setting the label
views.setTextViewText(, entry.getLabel());
// updating the widget because
appWidgetManager.updateAppWidget(appWidgetId, views);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.