Implementing the splash screen

SplashScreen class

Figure 49: Splash screen

The splash screen displays an image in the center of the screen and a red line around the edge (so that it looks good in all screen sizes). After it has drawn the screen the first time, it frees the image for garbage collection (by setting the reference to it to null) and calls back to the MIDlet. After three seconds or the first key press, it again calls back to the MIDlet. In this way, the MIDlet can do initialization while the splash screen is displayed.

  1. Create the SplashScreen class file.

  2. Import the required classes.

    // unnamed package
    import javax.microedition.lcdui.*;
    
  3. Set SplashScreen to extend Canvas and implement Runnable.

    class SplashScreen
        extends Canvas
        implements Runnable
    {
        private final SheepdogMIDlet midlet;
        private Image splashImage;
        private volatile boolean dismissed = false;
    
  4. Create the SplashScreen object.

        SplashScreen(SheepdogMIDlet midlet)
        {
            this.midlet = midlet;
            setFullScreenMode(true);
            splashImage = SheepdogMIDlet.createImage("/splash.png");
            new Thread(this).start();
        }
    
  5. Create the run method.

        public void run()
        {
            synchronized(this)
            {
                try
                {
                    wait(3000L);   // 3 seconds
                }
                catch (InterruptedException e)
                {
                    // can't happen in MIDP: no Thread.interrupt method
                }
                dismiss();
            }
        }
    
  6. Create the paint method to paint the screen.

        public void paint(Graphics g)
        {
            int width = getWidth();
            int height = getHeight();
            g.setColor(0x00FFFFFF);  // white
            g.fillRect(0, 0, width, height);
            g.setColor(0x00FF0000);  // red
            g.drawRect(1, 1, width-3, height-3);  // red border one pixel from edge
            if (splashImage != null)
            {
                g.drawImage(splashImage,
                            width/2,
                            height/2,
                            Graphics.VCENTER | Graphics.HCENTER);
                splashImage = null;
                midlet.splashScreenPainted();
            }
        }
    
    
  7. Create the two below methods to monitor key presses and to dismiss the screen.

        public synchronized void keyPressed(int keyCode)
        {
            dismiss();
        }
    
        private void dismiss()
        {
            if (!dismissed)
            {
                dismissed = true;
                midlet.splashScreenDone();
            }
        }
    }