Android Click on Widget not working after adding widget

假如想象 提交于 2019-12-09 13:51:13

问题


prefs.java

            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            setResult(RESULT_OK, resultValue);

            Context context = getApplicationContext();

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
            Intent configIntent = new Intent(context, Prefs.class);
            configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, configIntent, 
                                                            PendingIntent.FLAG_UPDATE_CURRENT);

            views.setOnClickPendingIntent(R.id.callbackwidget, pendingIntent);

            AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, views);

widget.xml

Problem is when i add widget IT IS NOT CLICKABLE. after rebooting phone it is working ok. also after deploying new build version, widget IS CLICKABLE

any ideas?


回答1:


great. problem was on NOT SENDING ACTION_APPWIDGET_UPDATE. so before closing preferences i send broadcast:

Intent updateIntent = new Intent(this, CallBackWidget.class);
updateIntent.setAction("PreferencesUpdated");
updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
sendBroadcast(updateIntent);

and in onreceive method of widget i check for broadcast

if ("PreferencesUpdated".equals(action)) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
appWidgetManager.updateAppWidget(appWidgetId, views);
int[] appWidgetIds = new int[] {appWidgetId};
onUpdate(context, appWidgetManager, appWidgetIds);
        }           

now it works like a charm ;)




回答2:


It might be that you have a config screen setup for your widget. If so then the widget is NOT built for you the first time it is added. Hard to tell from the code provided.

see http://developer.android.com/guide/topics/appwidgets/index.html. Specifically this sentence

The onUpdate() method will not be called when the App Widget is created (the system will not send the ACTION_APPWIDGET_UPDATE broadcast when a configuration Activity is launched). It is the responsibility of the configuration Activity to request an update from the AppWidgetManager when the App Widget is first created. However, onUpdate() will be called for subsequent updates—it is only skipped the first time.



来源:https://stackoverflow.com/questions/5167289/android-click-on-widget-not-working-after-adding-widget

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