我目前有一个使用两个setTextViewText
的小部件:
公共类DigitalClock扩展了AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
int N = appWidgetIds.length;
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.digitalclock);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent clockIntent = new Intent(context, DeskClock.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, clockIntent, 0);
views.setOnClickPendingIntent(R.id.rl, pendingIntent);
java.util.Date noteTS = Calendar.getInstance().getTime();
String time = "kk:mm";
String date = "dd MMMMM yyyy";
views.setTextViewText(R.id.tvTime, DateFormat.format(time, noteTS));
views.setTextViewText(R.id.tvDate, DateFormat.format(date, noteTS));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
我的问题是如何使用它来每秒设置两个TextView
,以便时间更新而不是appwidgetprovider
允许的30分钟?
我听说使用AlarmManager
,使用service
,handler
....问题似乎没有人说清楚,或举例说明我将如何做到这一点。
因此,如果有人有明确的方法来实现这一点,我将非常感谢,谢谢
答案 0 :(得分:3)
您可能在后台运行某些服务。将来自该服务或活动的广播消息发送到扩展AppWidgetProvider的类(在大多数情况下为DigitalClock),然后覆盖同一类的onReceive()函数。
步骤1:从服务或某处发送广播。
第2步:在你的DigitalClock类中添加onReceive()函数。
public class DigitalClock extends AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
int N = appWidgetIds.length;
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.digitalclock);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent clockIntent = new Intent(context, DeskClock.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, clockIntent, 0);
views.setOnClickPendingIntent(R.id.rl, pendingIntent);
java.util.Date noteTS = Calendar.getInstance().getTime();
String time = "kk:mm";
String date = "dd MMMMM yyyy";
views.setTextViewText(R.id.tvTime, DateFormat.format(time, noteTS));
views.setTextViewText(R.id.tvDate, DateFormat.format(date, noteTS));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
//Do your task here like updating the textviews
}
}