AppWidget Button onClick stops working

早过忘川 提交于 2019-12-12 17:06:40

问题


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

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