Android Widget button service does not respond to click

392 views Asked by At

Similar questions: service not starting on oreo in app widgetusing The closest to my question is Widget freezes after some time but is unanswered.

I have a simple widget button that should send a notification when pressed. It doesn't work when:

  1. I clear the app from recents just after opening the app on install
  2. randomly stops working sometimes (sometimes all the clicks are triggered together after I open the app again leading to a bunch of notifications getting fired together.)

From what all I have read so far, it looks to me as if the PendingIntent is getting cleared.

The code is mostly taken from the official app widget guide except for starting a Service instead of Activity.

WidgetProvider:

public class WidgetProvider extends AppWidgetProvider {

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        for (int appWidgetId : appWidgetIds) {
            Intent myIntent = new Intent(context, WidgetService.class);
            myIntent .setAction("SOME_UNIQUE_ACTION");
            PendingIntent pendingIntent = PendingIntent.getForegroundService(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
            views.setOnClickPendingIntent(R.id.button, pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}

WidgetService:

public class WidgetService extends JobIntentService {

    public WidgetService() {
        super();
    }

    @Override
    protected void onHandleWork(@Nullable Intent i) {
        Utils.sendNotification(); // this method works and is tested
    }
}

I tried both answers from here, Broadcast method didn't work and looked indirect as well, so I added #onCreate implementation to call startForeground, which didn't work either.

@Override
    public void onCreate() {
        super.onCreate();

        Utils.sendNotification();
        try {
            startForeground(1, notification);
        } catch (Error e) {
            Log.i(TAG, e.toString());
        }
    }
}

How do I get a button that will start a service reliably every time? Any help appreciated.

0

There are 0 answers