我是一位有用的助手,可以翻译文本。
我正在尝试构建一个小部件,它只包含一个按钮。我的目标是让按钮被点击后运行一些简单的代码(在我的测试中是 toast 弹窗)。最初看起来似乎没有问题,但突然间按钮停止响应点击。我注意到这通常发生在手机休眠后。以下是我的 AppWidgetProvider 代码。
onUpdate:
我正在尝试构建一个小部件,它只包含一个按钮。我的目标是让按钮被点击后运行一些简单的代码(在我的测试中是 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();
}
我有些困惑,如果有人能帮我指明正确的方向,我会非常感激。就像我说的那样,它在手机睡眠一两分钟后工作得很好,然后完全不响应点击。
谢谢!