I am developing an app with Kotlin in Android Studio which has a simple widget with two text views and a button. Every time the button is pressed, it fetches some data from a URL and updates the text views accordingly.
However, I’ve noticed that, if the screen is rotated or after some time passes, the button stops working, as if the pending intents had been discarded. I imagine I need to re-register the intents in some way, but I don’t know how.
Here is the code I’m using for the widget:
class AtbWidget : AppWidgetProvider() {
override fun onReceive(context: Context?, intent: Intent?) {
super.onReceive(context, intent)
if ("BUTTON_CLICK" == intent?.action) {
try {
updateAtbTransportTimes(context)
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
val views = RemoteViews(context.packageName, R.layout.atb_widget)
val updateWidgetIntent = Intent(context, AtbWidget::class.java).apply{
action = "BUTTON_CLICK"
}
val updateWidgetPendingIntent = PendingIntent.getBroadcast(
context,
appWidgetId,
updateWidgetIntent,
PendingIntent.FLAG_IMMUTABLE
)
views.setOnClickPendingIntent(R.id.button, updateWidgetPendingIntent)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
override fun onAppWidgetOptionsChanged(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int,
newOptions: Bundle
) {
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
val views = RemoteViews(context.packageName, R.layout.atb_widget)
val updateWidgetIntent = Intent(context, AtbWidget::class.java).apply{
action = "BUTTON_CLICK"
}
val updateWidgetPendingIntent = PendingIntent.getBroadcast(
context,
appWidgetId,
updateWidgetIntent,
PendingIntent.FLAG_IMMUTABLE
)
views.setOnClickPendingIntent(R.id.button, updateWidgetPendingIntent)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
1