After orientation change buttons on a widget are not responding [duplicate]

寵の児 提交于 2019-11-30 11:53:48

I eventually managed to recreate the OP's service-free solution. Here's the secret for the record: Any time you update the remote views, you must update everything that you ever update. My app was updating some visual elements, but not setting the button handler again. This caused the handler to stop working--not straight away--only after a rotation change, hence the confusion.

If this is done right, you don't need to intercept configuration change broadcasts, the last remote views you set will be used again after rotation. No call is needed to your AppWidgetProvider.

I had a similar issue, but my app is working well now with the solution suggested by Alex

"...solved without the help of a service, just setting again the setOnClickPendingIntent in the OnReceive method"

I tracked the onReceive method and it is called everytime I change the orientation of my device, so I called again the configuration of my widget on the onReceive method.

Anyway Im not sure this is the best solution to solve that problem, if anyone knows a better solution please share.

Thanks.

Whenever you update the look of your widget (using either an Activity or your Broadcast Receiver [App widget provider]), you must also reassign all the PendingIntents for the click handlers, and then call updateAppWidget() as normal.

Example with setTextViewText():

// This will update the Widget, but cause it to
// stop working after an orientation change.
updateWidget()
{
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
remoteViews.setTextViewText(R.id.widget_text_view, "Updated widget");

appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}


// This is the correct way to update the Widget,
// so that it works after orientation change.
updateWidget()
{
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
remoteViews.setTextViewText(R.id.widget_text_view, "Updated widget");

Intent intent = new Intent(context, MyWidgetActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, ...);
remoteViews.setOnClickPendingIntent(R.id.widget_click_button, pendingIntent);

appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!