Android Click on Widget not working after adding w

2020-06-28 12:36发布

问题:

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.