AppWidget 按钮 onClick 停止工作

发布于 2024-11-04 06:39:16 字数 975 浏览 4 评论 0原文

我正在尝试构建一个仅包含一个按钮的小部件。我想要做的是单击按钮,然后运行一些简单的代码(在我的测试中它是一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

下雨或天晴 2024-11-11 06:39:16

每次使用后,待处理的意图都会被“烧毁”。您需要重新设置它。或者等待小部件刷新,然后它也会发生,但这可能不是理想的方式。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文