每秒钟定期更新小部件



我目前有一个使用两个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 ....问题是,似乎没有人能说清楚,也没有人能举例说明我该怎么做。

如果有人有一个明确的方法来完成这个,我将非常感激,谢谢

您可能在后台运行一些服务。从该服务或活动发送广播消息到扩展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
}
    }

相关内容

  • 没有找到相关文章

最新更新