Im trying to make an android widget which the user can refresh the content on by clicking a button. Im stuck.
Currently neither the scheduled refresh or the button seems to work. Is there anyone out there which either can see what Im doing wrong, or has some code examples which does something similar to what I attempt to do?
class Widget : AppWidgetProvider() {
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
Log.d("WIDGET","UPDATE")
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
override fun onEnabled(context: Context) {
// Enter relevant functionality for when the first widget is created
}
override fun onDisabled(context: Context) {
// Enter relevant functionality for when the last widget is disabled
}
}
internal fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
Log.d("WIDGET","1")
val widgetText = (0..10).random().toString()
val views = RemoteViews(context.packageName, R.layout.widget)
views.setTextViewText(R.id.txtWidget, widgetText)
val intentSync = Intent(context, Widget::class.java)
intentSync.action =
AppWidgetManager.ACTION_APPWIDGET_UPDATE
val pendingSync = PendingIntent.getBroadcast(
context,
0,
intentSync,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
) //You need to specify a proper flag for the intent. Or else the intent will become deleted.
views.setOnClickPendingIntent(R.id.buttonWidget, pendingSync)
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
}