Sunday, April 18, 2010

Create a Apps to Show Digital Time in Android

this blog helps to create a simple digital clock in andriod.

Create a Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:id="@+id/countdown" android:layout_width="320dip"
        android:layout_height="120dip" android:text="00:00:00"
        android:textSize="15pt" android:textColor="#00C2FF"
        android:layout_centerInParent="true" />
</RelativeLayout>


Create Activty Class for show the Time

public class MainActivity extends Activity {
    private TextView countdown;
    private Timer timer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView countdown = (TextView) findViewById(R.id.countdown);
    }

    @Override
    protected void onStart() {
        super.onStart();
        timer = new Timer("DigitalClock");
        Calendar calendar = Calendar.getInstance();

        // Get the Current Time
        final Runnable updateTask = new Runnable() {
            public void run() {
                countdown.setText(getCurrentTimeString());
            }
        };

        // update the UI
        int msec = 999 - calendar.get(Calendar.MILLISECOND);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(updateTask);
            }
        }, msec, 1000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        timer.cancel();
        timer.purge();
        timer = null;
    }

    private String getCurrentTimeString() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return String.format("%02d:%02d:%02d %02d", hour, minute, second);
    }
}

No comments:

Post a Comment