1

I'm trying to have my widget use an onClick action to prompt a refresh. I found some demo code that works, but it opens a URI in browser. I'm having trouble replacing the URI action with something simpler, like displaying a toast. I've marked the line that I'm trying to change, but I don't know how to make Android set a different action other than Action.VIEW.

public class NewAppWidget extends AppWidgetProvider {

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

    //I AM TRYING TO CHANGE THIS INTENT
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com/"));
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

    views.setOnClickPendingIntent(R.id.refresh, pendingIntent);
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

@Override //Nothing changed here
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    for (int appWidgetId : appWidgetIds) {
        updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }
}

The specific lines are

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com/"));
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Sunny
  • 3,134
  • 1
  • 17
  • 31
Bryan W
  • 1,112
  • 15
  • 26

1 Answers1

0

I got this to work completely unexpectedly. I followed this post but left my intent declarations where they were. The resulting lines were:

Intent intent = new Intent(context, NewAppWidget.class);
        intent.setAction(refresh);
        intent.putExtra("appWidgetId", appWidgetId);

        views.setOnClickPendingIntent(R.id.refresh, PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_UPDATE_CURRENT));
        appWidgetManager.updateAppWidget(appWidgetId, views);

followed by onReceive:

@Override
    public void onReceive(Context context, Intent intent) {
        if(refresh.equals(intent.getAction())) {
            Toast.makeText(context, "Clicked", Toast.LENGTH_LONG).show();
        }
    }

Edit for clarity: intent.getAction() needs to be a registered action within the receiver's intent filter.

Bryan W
  • 1,112
  • 15
  • 26