小工具在几分钟后停止更新

时间:2013-04-01 20:41:06

标签: android timer widget textview handler

我开发了一个小部件,使用TextView两个timer显示时间和日期,每秒更新一次:

final Handler handler = new Handler();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            handler.post(new Runnable() {
                    public void run() {
                        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);
                    }
            });
    }
}, 0, 1000);// Update textview every second

它在添加时更新小部件,但在几分钟后停止。我重新启动后也很难加载,但主要问题是似乎timer在这么多分钟后停止了...... 有谁知道发生了什么?感谢

1 个答案:

答案 0 :(得分:0)

由于app小部件只是主屏幕进程托管的广播接收器,因此您必须使用AlarmManager来安排对小部件的调用。如果不仅仅是测试,请注意您的电池会耗尽,因为设备永远不会进入睡眠状态。通常,每秒更新app小部件并不是一个好主意。

可以这样做(这里是一分钟醒来),类似于这段代码

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MyWidget.ACTION_MYACTION);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
long triggerAtTime = getNextOccurrence(1); // next minute
am.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pi);

static private long getNextOccurrence(int deltaMinutes)
    {
            Calendar calendar = Calendar.getInstance();
            long now = calendar.getTimeInMillis();
            long then = now + (deltaMinutes * 60 * 1000);
            return then;
    }
OnReceive

中的

public void onReceive(Context context, Intent intent)
    {
            Log.d(TAG, "onReceive() " + intent.getAction());
            super.onReceive(context, intent);

            if (intent != null)
            {
                    if (ACTION_MYACTION.equals(intent.getAction())
                    {
                            updateWidgets(context);
                    }
             ...