0

I've an app widget which I would like to print text("OnClicked") to console(or toast) ONLY when the widget is clicked. i.e, I would NOT want the text to be printed when the device is restarted as currently happening.

  1. Is there a way to trigger some method ONLY when the widget is clicked? If so, then how?
  2. In a case that I want to do my action only when the widget is clicked: Do I need to set updatePeriodMillis by 0 value? (android:updatePeriodMillis="0")

This is the implementation of my appwidgetprovider

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

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // Get all ids
        ComponentName thisWidget = new ComponentName(context,
                MyWidgetProvider.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        for (int widgetId : allWidgetIds) {
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                    R.layout.my_widget_provider_layout);
            // Register an onClickListener
            Intent intent = new Intent(context, MyWidgetProvider.class);
            intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                    0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.main_layout, pendingIntent);
            appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }


        Log.d("TAG", "OnClicked");
    }

and this is the manifest part:

<receiver android:name="com.example.MyWidgetProvider" >
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>
    <meta-data android:name="android.appwidget.provider"
        android:resource="@xml/my_widget_info" />
</receiver>
Maor Cohen
  • 936
  • 2
  • 18
  • 33
  • 1
    Don't use `onUpdate()` and `ACTION_APPWIDGET_UPDATE` for your click handler. Use a different action `String` (or none at all) and check `intent.getAction()` in `onReceive()`. If it's your action `String` (or null), do your log print/`Toast`. If it's not yours, call `super.onReceive(context, intent);`. – Mike M. Nov 16 '19 at 14:35
  • Thanks! It works! And can you please answer my second question? – Maor Cohen Nov 16 '19 at 14:50
  • 1
    Well, since you're only performing your click handling when it's your action `String`, it's not going to happen for anything else. All of the other `Intent`s will be passed to the `super`, so it doesn't really matter what the update frequency is. – Mike M. Nov 16 '19 at 14:59

0 Answers0