如何每秒刷新小部件?

时间:2012-02-10 10:37:48

标签: android widget refresh seconds

看下面的代码我需要每秒更新一次这个onUpdate方法,有人能给出一些好的例子吗?主要是我需要将代码从CurFreq(context);更新为views.setTextViewText(R.id.text_widget_batt, prefNameBattery+"%");

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            Intent intent = new Intent(context, MyActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
            views.setOnClickPendingIntent(R.id.layout_widget, pendingIntent);

            CurFreq(context);
            Temp(context);
            Battery(context);

            SharedPreferences myPrefsInfo = context.getSharedPreferences("myPrefsInfo", Context.MODE_PRIVATE);
            String prefNameCurFreq = myPrefsInfo.getString(WidgetCurFreq, "");
            String prefNameTemp = myPrefsInfo.getString(WidgetTemp, "");
            String prefNameBattery = myPrefsInfo.getString(WidgetBattery, "");

            views.setTextViewText(R.id.text_widget_freq, prefNameCurFreq);
            views.setTextViewText(R.id.text_widget_temp, prefNameTemp+",0°C");
            views.setTextViewText(R.id.text_widget_batt, prefNameBattery+"%");

            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
}

1 个答案:

答案 0 :(得分:-1)

您可以编写服务代码并实现计时器,并相应地每秒更新一次窗口小部件。 在计时器中使用OnStartCommand(Intent,int,int)服务方法调用您的方法。