3D-kreativ
3D-kreativ

Reputation: 9297

How to create a stopwatch

I'm learning Android and since I'm a beginner I thought it could be appropriate to make some kind of stopwatch as my first app. I also need one since I want to measure my long walks.

I have done the part with the buttons and all that stuff, now I'm not sure how to get this time thing to get hours, minutes and seconds to update the textView?

I also wonder how I should do to get calls to a method, like each, 30 minutes?

Preciate some guidance and hints! Thanks!

Upvotes: 0

Views: 535

Answers (1)

ITCuties
ITCuties

Reputation: 219

Just create a thread for that task the same as we did here: http://www.itcuties.com/android/how-to-create-android-splash-screen/

Let's modify our code a little bit :)

public class MainActivity extends Activity {

    private static String TAG = MainActivity.class.getName();
    private static long SLEEP_TIME = 1; // Sleep for some time

    private TextView hoursText;
    private TextView minutesText;
    private TextView secondsText;

    // TODO: time attributes

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        hoursText = (TextView) findViewById(R.id.hoursView);
        minutesText = (TextView) findViewById(R.id.minutesView);
        secondsText = (TextView) findViewById(R.id.secondsView);

        // TODO: Get start time here

        // Start timer and launch main activity
        ClockUpdater clockUpdater = new ClockUpdater();
        clockUpdater.start();
    }

    private class ClockUpdater extends Thread {
        @Override
        /**
         * Sleep for some time and than start new activity.
         */
        public void run() {
            try {
                // Sleeping
                while (true) {
                    Thread.sleep(SLEEP_TIME * 1000);
                    // TODO: Get current time here

                    // current time - start time ...

                    // Set new values
                    hoursText.setText("10"); // don't know if you walk this long
                                                // :)
                    minutesText.setText("10");
                    secondsText.setText("10");
                }

            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }

        }
    }
}

Upvotes: 1

Related Questions