2

I want to refresh a TextView's text per minute when Digital Clock refresh the time with the format hh/mm every minute. I put a TextView named txtView1 in the Activity and create a class Digital Clock.When I run the app,However,the app exits with error.I really don't konw why here is the important function onAttachedToWindow() about the 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();

    }
Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
信红 吴
  • 29
  • 1

1 Answers1

0

The system sends a broadcast event at the exact beginning of every minutes based on system clock. The most reliable way is to do it like this :

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);
}

Don't forget however to initialize your TextView beforehand (to current system time) since it is likely you will pop your UI in the middle of a minute and the TextView won't be updated until the next minute happens.

Alex
  • 2,893
  • 25
  • 24