AppWidget 按钮 onClick 停止工作
我正在尝试构建一个仅包含一个按钮的小部件。我想要做的是单击按钮,然后运行一些简单的代码(在我的测试中它是一个 toast 警报)。最初似乎工作正常,但突然按钮停止响应点击。手机休眠后我一直注意到这一点。这是我的 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 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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.