问题
I have a widget I'm trying to build that consists of only a button. What I'm wanting to do is have the button clicked and then run some simple piece of code (in my test it's a toast alert). It seems to work fine initially, but suddenly the button stops responding to clicks. I've noticed it consistently after the phone has been asleep. Here is my code for the AppWidgetProvider.
onUpdate:
for (int appWidgetId : appWidgetIds) {
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.my_widget);
Intent intent = new Intent(context, MyNewWidgetProvider.class);
intent.setAction("MyCode");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteView.setOnClickPendingIntent(R.id.my_btn, pendingIntent);
AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, remoteView);
}
onReceive:
super.onReceive(context, intent);
if (intent.getAction().equals("MyCode")) {
Toast toast = Toast.makeText(context, "It worked", Toast.LENGTH_SHORT);
toast.show();
}
I'm rather stumped, so if anyone can help point me in the right direction I would appreciate it. Like I said, it works fine until the phone is asleep for a minute or two, then it completely stops responding to clicks.
Thank You!
回答1:
The pending intent is "burned" after each use. You need to set it again. Or wait for the widget to get refreshed, then it happens, too, but that's probably not the desired way.
来源:https://stackoverflow.com/questions/5851634/appwidget-button-onclick-stops-working