Skip to content Skip to sidebar Skip to footer

Making A Interval Timer In Java Android

I have plans to create an interval app using timers. It should just be the most basic So I'll have to add some more when I've understood the basics. What I want to achieve is to s

Solution 1:

I would always recommend using a Handler.

It's a little more work than the built in classes, but I find that it is vastly more efficient and you have more control over it.

The Handler is a class that will handle code execution over a specific Looper / Thread by default, the Thread it is created in, Otherwise you can specify where the Handler executes its code by passing in the Looper to the Handler constructor like - new Handler(Looper.getMainLooper());

The reason I would recommend the looper is because you have a higher flexibility of control, as it is a slightly lower down abstraction over the TimerTask methods.

Generally they are very useful for executing code across threads. E.g. useful for piping data across threads.

The two main uses are:

publicvoidonCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    finalHandlerh=newHandler();
    h.postDelayed(newRunnable()
    {
        privatelongtime=0;

        @Overridepublicvoidrun()
        {
            // do stuff then// can call h again after work!
            time += 1000;
            Log.d("TimerExample", "Going for... " + time);
            h.postDelayed(this, 1000);
        }
    }, 1000); // 1 second delay (takes millis)
}

Simple use!

Or you can use messages, which reduce object creation. If you are thinking about high speed updating UI etc - this will reduce pressure on the garbage collector.

classMainActivityextendsActivity {

    @OverridepublicvoidonCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        MyTimerstimer=newMyTimers();
        timer.sendEmptyMessage(MyTimers.TIMER_1);
        timer.sendEmptyMessage(MyTimers.TIMER_2);

    }


    publicstaticclassMyTimersextendsHandler
    {

        publicstaticfinalintTIMER_1=0;
        publicstaticfinalintTIMER_2=1;

        @OverridepublicvoidhandleMessage(Message msg)
        {
            switch (msg.what)
            {
                case TIMER_1:
                    // Do something etc.
                    Log.d("TimerExample", "Timer 1");
                    sendEmptyMessageDelayed(TIMER_1, 1000);
                    break;
                case TIMER_2:
                    // Do another time update etc..
                    Log.d("TimerExample", "Timer 2");
                    sendEmptyMessageDelayed(TIMER_2, 1000);
                    break;
                default:
                    removeMessages(TIMER_1);
                    removeMessages(TIMER_2);
                    break;
            }
        }
    }
}

Obviously this is not a full implementation but it should give you a head start.

Post a Comment for "Making A Interval Timer In Java Android"