2

当数字时钟每分钟刷新一次格式的时间时,我想每分钟刷新一个 TextView 的文本hh/mm。我在Activity中放置了一个名为txtView1的TextView并创建了一个类Digital Clock。当我运行应用程序时,应用程序退出并出错。我真的不知道为什么这里是onAttachedToWindow()关于Digital Clock的重要功能:

 protected void onAttachedToWindow() {
       mTickerStopped = false;

        super.onAttachedToWindow();

        mHandler = new Handler();


        /**

         * requests a tick on the next hard-second boundary

         */

        mTicker = new Runnable() {

                public void run() {

                    if (mTickerStopped) return;

                    mCalendar.setTimeInMillis(System.currentTimeMillis());

                    String content = (String) DateFormat.format(mFormat, mCalendar);

                    if(content.split(" ").length > 1){



                        content = content.split(" ")[0] + content.split(" ")[1];

                    }

                    setText(android.text.Html.fromHtml(content));

                   //-----Here is the TextView I want to refresh

                   TextView txtV1 = (TextView)findViewById(R.id.txtView1);
                   txtV1.setText("Now Fresh");//Just for try,so set a constant string 

                    invalidate();

                    long now = SystemClock.uptimeMillis();

                    //refresh each minute

                    long next = now + (60*1000 - now % 1000);

                    mHandler.postAtTime(mTicker, next);

                }

            };

        mTicker.run();

    }
4

1 回答 1

0

系统根据系统时钟在每分钟的确切开始发送广播事件。最可靠的方法是这样做:

BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;

@Override
public void onStart() {
    super.onStart();
    _broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context ctx, Intent intent) {
                if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
                    _tvTime.setText(_sdfWatchTime.format(new Date()));
            }
        };

    registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

@Override
public void onStop() {
    super.onStop();
    if (_broadcastReceiver != null)
        unregisterReceiver(_broadcastReceiver);
}

但是不要忘记预先初始化您的 TextView(到当前系统时间),因为您可能会在一分钟的中间弹出您的 UI,并且 TextView 直到下一分钟才会更新。

于 2013-07-14T19:19:00.397 回答