0

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)
}
  • Not sure about the first one, but `onUpdate()` won't run for your button unless the `Intent` has an `IntArray` extra of the App Widget IDs. I can't find an example in Kotlin atm, but here it is in Java: https://stackoverflow.com/a/49028938. You can use `context` in place of `getApplication()` there, and make sure to use `EXTRA_APPWIDGET_IDS` _plural_, not `EXTRA_APPWIDGET_ID`. – Mike M. Jan 18 '23 at 21:14

0 Answers0