Timer and TimerTask example in J2ME

By: Emiley J. Emailed: 1766 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This sample J2ME program demonstrates the use of Timer and TimerTask in a midlet. This MIDlet creates two gauges. One gauge gaugeOne,  sets elements from low to high. The other, gaugeTwo, set elements from high to low. In effect, this has gaugeOne "going up", and gaugeTwo "going down."

The two timers fire at different intervals.
 
There are two commands on our form:

  1. OK: toggles whether the times are active or not.
  2. EXIT: exits the MIDlet.

/*
 * Copyright (c) 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
 */

import java.lang.*;
import java.io.*;
import java.util.*;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class TimerMIDlet extends MIDlet implements CommandListener {
    // number of elements in gauge
    final private static int GAUGE_MAX = 10;

    private boolean timersRunning; // tracks state of timers
    private Display myDisplay;     // handle to the display

    private Gauge gaugeOne;        // "going up" gauge
    private Gauge gaugeTwo;        // "going down" gauge

    private Form myScreen;         // form on which to 
                                   // place gauges
    private Command cmdOK;         // OK command
    private Command cmdExit;       // EXIT command

    private Timer timer;
    private MyTimerTask timerTaskOne;
    private MyTimerTask timerTaskTwo;

    /**
     * Internal class that provides a TimerTask.
     */
    private class MyTimerTask extends TimerTask {
        private Gauge myGauge; // reference to gauge
        private boolean goUp;  // if true, go up
        private int num;       // number of times called

        /**
         * Public constructor: stores "direction" and a reference to
         * a gauge.
         */
        public MyTimerTask(Gauge g, boolean up) {
            myGauge = g;
            goUp = up;
        }

        /**
         * As the timer fires, this method is invoked. Set gauge
         * based on goUp
         */
        public void run() {
            num++;
            myGauge.setValue(goUp ?
                             GAUGE_MAX -(num % GAUGE_MAX) :
                             num % GAUGE_MAX);
        }
    }

    /**
     * Public constructor: gets handle to display,
     * creates form, gauges, and commands.
     */
    public TimerMIDlet() {
        myDisplay = Display.getDisplay(this);
        myScreen = new Form("TimerMIDlet");
        gaugeOne = new Gauge("Up Gauge",
                             false,
                             GAUGE_MAX,
                             0);
        myScreen.append(gaugeOne);

        gaugeTwo = new Gauge("Down Gauge",
                             false,
                             GAUGE_MAX,
                             GAUGE_MAX);
        myScreen.append(gaugeTwo);

        cmdOK = new Command("OK", Command.OK, 1);
        cmdExit = new Command("Exit", Command.EXIT, 1);
        myScreen.addCommand(cmdOK);
        myScreen.addCommand(cmdExit);
        myScreen.setCommandListener(this);
    }

    /**
     * Changes the state of timers to/from active to/from
     * not-active.
     */
    private void flipFlop() {
        if (timersRunning) {
            timerTaskOne.cancel();
            timerTaskTwo.cancel();
            timer.cancel();
            timersRunning = false;
        } else {
            timer = new Timer();
            timerTaskOne = new MyTimerTask(gaugeOne, false);
            timerTaskTwo = new MyTimerTask(gaugeTwo, true);
            timer.schedule(timerTaskOne, 0, 1000);
            timer.schedule(timerTaskTwo, 0, 1500);
            timersRunning = true;
        }
    }

    /**
     * Called by the system to start our MIDlet.
    * @exception MIDletStateChangeException
     */
    protected void startApp() throws MIDletStateChangeException {
        myDisplay.setCurrent(myScreen);
        flipFlop();
    }

    /**
     * Called by the system to pause our MIDlet.
     * No actions required by our MIDLet.
     */
    protected void pauseApp() {}

    /**
     * Called by the system to end our MIDlet.
     * No actions required by our MIDLet.
     */
    protected void destroyApp(boolean unconditional) {}

    /***
     * Respond to command selections. Process two commands:
     * 
     * OK: flip flop the timers to/from active
     * EXIT: exit this MIDlet
     * 
     */
    public void commandAction(Command c, Displayable d) {
        if (c == cmdOK) {
            flipFlop();
        } else if (c == cmdExit) {
            destroyApp(false);
            notifyDestroyed();
        }
    }
}

J2ME Home | All J2ME Tutorials | Latest J2ME Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(2)


1. View Comment

the website is good and nice helps a lot add more j2me examples as you can

View Tutorial          By: wkkjnj at 2010-07-20 04:34:13
2. View Comment

Oh, Thanks for your code, but I think you should add some result images to improve your article :)

View Tutorial          By: Songokute at 2013-01-29 13:55:13

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Emiley J.
Error generating R.java from manifest
ERROR 1251: Client does not support authentication protocol requested by server; consider upgrading MySQL client
IIS and Tomcat - how to configure to work together
PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......
Adding your own Application icon for your J2ME application (jar file)
Creating Menus in Code using VB.net
Traversing all files in a directory using Ruby
Using Proxy to connect to URLs in Ruby
POST a form in Ruby
Reading URL content using Ruby (HTTP)
dRuby client/server mode sample program
Benchmark module in Ruby
encoding and decoding in Ruby using Base64 Module
Module Abbrev in Ruby
Standard Library Packages in Ruby

More Tutorials in J2ME
Code sample to Send SMS from a J2ME application.
Adding your own Application icon for your J2ME application (jar file)
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
Datagrams in J2ME (UDP Programming sample)
Client Server in J2ME (Socket Programming sample)
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
Using HTTP vs UDP vs Socket in J2ME
RMSCookieConnector - Using Cookies in J2ME
POST UTF-8 encoded data to the server in J2ME
lists, forms, choices, gauges, text fields, text boxes in J2ME
Using List to create a Menu and Menu items in J2ME
Using alerts and tickers in J2ME
J2ME Canvas sample to show games programming in J2ME
Timer and TimerTask example in J2ME
List of GPRS Access points for all countries

More Latest News
Most Viewed Articles (in J2ME )
What is J2ME?
Sample J2ME code that shows various functionality of RMS.
java.lang.SecurityException: MIDP lifecycle does not support system exit.
How to get the CLDC and MIDP version from a J2ME program
StringItem sample program in J2ME
Gauge sample program in J2ME
Sample program to draw a rectangle in J2ME
translate() Sample program in J2ME
'double buffering' Sample program in J2ME
A sample J2ME Auto-resume program.
getPosition() the right strategy in getting GPS
J2ME Canvas sample to show games programming in J2ME
Timer and TimerTask example in J2ME
Using alerts and tickers in J2ME
Download a file over a network in J2ME midlet
Most Emailed Articles (in J2ME)
How to load J2ME applications to the IDEN handsets
GUI components and menu based J2ME Applications.
Ticker sample program in J2ME
Using List to create a Menu and Menu items in J2ME
What is J2ME?
'LINK.EXE' is not recognized as an internal or ext
DateField sample program in J2ME
Sample program to draw a rectangle in J2ME
Types of configurations in J2ME
Types of Profiles in J2ME
A sample J2ME Auto-resume program.
getPosition() the right strategy in getting GPS
Client Server in J2ME (Socket Programming sample)
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
What is J2ME?