简体   繁体   中英

APP Widget Textview not updating (Java, android studio)

I am trying to update textview in an app widget but nothing is refreshing

    @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    for(int appWidgetID : appWidgetIds){
        Intent intent = new Intent(context, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0);
        RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.timetable_widget);
        views.setOnClickPendingIntent(R.id.btnPress,pendingIntent);
        views.setTextViewText(R.id.textView2, "HELLO__WORLD");
        appWidgetManager.updateAppWidget(appWidgetID,views);


    }
}

Do you really receive an update broadcast? The update time for widgets is forced to at least 30mins, like this:

<appwidget-provider
    ...
    android:updatePeriodMillis="xxx" // if set a millis less than 30mins, it will not work
    ...
/>

Or set the updatePeriodMillisupdate to 0 and update widget by sending custom broadcast:

  1. Register intent-filter of your action
  2. Receive your action in your widget' s onReceive and update the text

To prevent any ANR timeouts, we perform the update in a service.

fun updateWidget(context: Context) {
    val appWidgetManager = AppWidgetManager.getInstance(context)
    val widgetComponentName = ComponentName(context.packageName, YourWidget::class.java.name)
    val appWidgetIds: IntArray = appWidgetManager.getAppWidgetIds(widgetComponentName)
    RemoteViews(context.packageName, R.layout.your_widget).apply {
        setTextViewText(R.id.text, "new text")
        appWidgetManager.updateAppWidget(appWidgetIds, this)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM