我制作了一个有图像并显示时间的小部件。 howerver,时间无法更新。所以我尝试实现,当用户点击小部件时,时间将更新。 我发现一些教程说使用setOnClickPendingIntent可以做到这一点,但我的代码不起作用。
任何解决方案都可以让小部件更新时间onClick或自动更新?
public class NewAppWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());;
// Construct the RemoteViews object
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
Intent intent = new Intent(context, NewAppWidget.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
updateViews.setOnClickPendingIntent(R.id.imageView, pendingIntent);
updateViews.setTextViewText(R.id.editText2, widgetText);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
答案 0 :(得分:0)
像这样改变你PendingIntent
Intent intent = new Intent()
intent.putExtra(EXTRA_VALUES, values)
intent.setComponent(new ComponentName(context, NewAppWidget.class));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);