开发者

Own digital clock with data und time. efficiently

Yesterday I programmed an own digital clock. I used the google blog: http://android-developers.blogspot.com/2007/11/stitch-in-time.html for help.

The following code is the resulat.

My question. Is it a efficient way, to update the handle by SystemClock.uptimeMillis()? I thought it would be better to habe something like a listener for change on time.

Second question. Is it effienc for the processor to use DateFormat.getTimeInstance() command to get the time? I use it because I don't know how to calculate the actual time from System.currentTimeMillis().

public class TextClock extends Activity {

    private TextView mTimeLabel;
    private Handler mHandler = new Handler();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setCont开发者_如何学JAVAentView(R.layout.main);
            mTimeLabel = (TextView) findViewById(R.id.timeLabel);
    }

    private Runnable mUpdateTimeTask = new Runnable() {
               public void run() {
                   String currentTimeString = DateFormat.getTimeInstance().format(new Date());
                   String currentDateString = DateFormat.getDateInstance().format(new Date());
                   mTimeLabel.setText(currentDateString + "\n" + currentTimeString);

                   mHandler.postAtTime(this, (SystemClock.uptimeMillis() + 1000));
               }
            };

        @Override
            protected void onStart()
            {
                    super.onPause();
            mHandler.removeCallbacks(mUpdateTimeTask);
            mHandler.postDelayed(mUpdateTimeTask, 100);
            }

            @Override
            protected void onPause()
            {
                    super.onPause();
                    mHandler.removeCallbacks(mUpdateTimeTask);
            }
} 

Thank you for your comments.

Felix


Keep in mind this saying: "Premature optimization is the root of all evil" In other words, if it ain't broke, don't fix it. When you are writing a clock application, small performance optimizations are unlikely to make a big difference to the user experience.

  1. I don't see a problem with using SystemClock.uptimeMillis() the way you are using it. Listeners are generally for events that happen irregularly, rather than routine (time-based) events.
  2. It would probably be very, very, very slightly faster to manually parse the time from System.currentTimeMillis(), because there would be less function calls involved and less memory allocation (both of which have some overhead, especially in Java), however the savings would be tiny.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜