Search code examples
androidandroid-serviceandroid-widgetforeground-serviceandroid-11

Widget can't start a service on device boot on Android 11 until some activity is launched


val startServiceIntent = TestService.getServiceIntent(context).let {
    PendingIntent.getService(context, 0, it, PendingIntent.FLAG_UPDATE_CURRENT)
}
val views = RemoteViews(context.packageName, R.layout.layout_app_widget).apply {
    setOnClickPendingIntent(R.id.start_service_btn, startServiceIntent) // doesn't work on boot device
    setOnClickPendingIntent(R.id.start_activity_btn, startActivityIntent) // works fine
}
appWidgetManager.updateAppWidget(appWidgetId, views)

How to treat such behaviour? How can I at least show a message to a user that a service can't be started from widget until he launches the app (make it visible) or launch an activity instead during this device session?

Because now nothing happens when I press the button to start the service until I launch the app at least once

Is there any method on Android 11 to check if we can start foreground service, camera and so on from background / widget? How to find out that user has launched an activity of app at least once for the current session of the device?


Solution

  • Based on @CommonsWare comment I need to use PendingIntent.getForegroundService() instead of PendingIntent.getService()