我通过.setOnClickPendingIntent将挂起的意图附加到窗口小部件按钮,并且单击按钮时没有响应。奇怪的是,当我在下载服务中实现相同的代码时,它想工作(但不会因为该服务在一个循环中运行多个周期而使活动突然弹出并在单击按钮时消失)。 / p>
我需要它能够在我的主线程上运行,但是如果我弄清楚为什么它未按预期进行调用,那将无法终生。
在以下方法中,侦听器已连接到RemoteViews按钮:
public static void updateWidget(Context context, AppWidgetManager appWidgetManager, int widgetId) {
mContext = context;
RemoteViews widgetViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
// Create a PendingIntent to open the config activity
Intent configIntent = new Intent(context, ConfigActivity.class);
configIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
// Keep in mind PendingIntent uniqueness rules. Use the widget ID as a request code
PendingIntent configPendingIntent = PendingIntent.getActivity(context, widgetId, configIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Attach the PendingIntent to our config button
widgetViews.setOnClickPendingIntent(R.id.configButton, configPendingIntent);
appWidgetManager.updateAppWidget(widgetId, widgetViews);
if(loadChached() != null) {
Weather weather = loadChached();
widgetViews.setTextViewText(R.id.conditionsDisplay, weather.getConditions());
widgetViews.setTextViewText(R.id.tempDisplay, String.valueOf(weather.getDisplayTemp()));
widgetViews.setTextViewText(R.id.timestampDisplay, weather.getTimeStamp());
if(loadPreferences(context).equals("Dark")) {
Log.i(TAG, "updateWidget: Activating Dark Theme");
widgetViews.setTextColor(R.id.conditionsDisplay, context.getResources().getColor(android.R.color.background_dark));
widgetViews.setTextColor(R.id.tempDisplay, context.getResources().getColor(android.R.color.background_dark));
widgetViews.setTextColor(R.id.timestampDisplay, context.getResources().getColor(android.R.color.background_dark));
}
else if(loadPreferences(context).equals("Light")) {
Log.i(TAG, "updateWidget: Activating Light Theme");
widgetViews.setTextColor(R.id.conditionsDisplay, context.getResources().getColor(android.R.color.white));
widgetViews.setTextColor(R.id.tempDisplay, context.getResources().getColor(android.R.color.white));
widgetViews.setTextColor(R.id.timestampDisplay, context.getResources().getColor(android.R.color.white));
}
appWidgetManager.updateAppWidget(widgetId, widgetViews);
}
Intent updateIntent = new Intent(context, DownloadIntentService.class);
updateIntent.setAction(WeatherWidgetProvider.ACTION_UPDATE_WEATHER);
Log.i(TAG, "onUpdate: Starting Service");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
context.startForegroundService(updateIntent);
}
catch (Exception e) {
e.printStackTrace();
}
}
else {
try {
context.startService(updateIntent);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
我要启动的活动已使用意向过滤器注册在清单中:
<activity android:name=".ConfigActivity">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
非常感谢您的协助。
答案 0 :(得分:0)
问题是我也从服务中调用.updateWidget,覆盖了提供程序中添加到它的所有内容。将所有更新移回主线程后,问题已解决。