Java/J2ME/Basics

Материал из Java эксперт
Перейти к: навигация, поиск

Basic MIDlet Shell

   <source lang="java">

import javax.microedition.midlet.MIDlet; public class BasicMIDletShell extends MIDlet {

 public void startApp() {
   System.out.println(getAppProperty("Model-Version"));
 }
 public void pauseApp() {
 }
 public void destroyApp(boolean unconditional) {
 }

}

      </source>
   
  
 
  



Example jad file

   <source lang="java">

MIDlet-Name: Hello World MIDlet-Version: 1.0 MIDlet-Vendor: Jim MIDlet-Description: My First MIDlet suite MIDlet-1: HelloWorld, /greeting/myLogo.png, greeting.HelloWorld MIDlet-Jar-URL: HelloWorld.jar MIDlet-Jar-Size: 1428


      </source>
   
  
 
  



Example MIDlet

   <source lang="java">

/* J2ME in a Nutshell By Kim Topley ISBN: 0-596-00253-X

  • /

import java.util.Timer; import java.util.TimerTask; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class ExampleMIDlet extends MIDlet {

   // Flag to indicate first call to startApp
   private boolean started = false;
   
   // Background thread
   private Thread thread;
   
   // Timer interval
   private int timerInterval;
   
   // Timer
   private Timer timer;
   
   // Task to run via the timer
   private TimerTask task;
   
   // Required public constructor. Can be
   // omitted if nothing to do and no other
   // constructors are created.
   public ExampleMIDlet() {
       System.out.println("Constructor executed");
       
       // Get the timer interval from the 
       // manifest or JAD file.
       String interval = getAppProperty("Timer-Interval");
       timerInterval = Integer.parseInt(interval); 
       System.out.println("Timer interval is " + interval);
   }
       
   protected void startApp() throws MIDletStateChangeException {
       if (!started) {
           // First invocation. Create and start
           // a timer.
           started = true;            
           System.out.println("startApp called for the first time");
           startTimer();
       } else {
           // Resumed after pausing. 
           System.out.println("startApp called following pause");
       }
       
       // In all cases, start a background thread.
       synchronized (this) {
           if (thread == null) {
               thread = new Thread() {
                   public void run() {
                       System.out.println("Thread running");
                       while (thread == this) {
                           try {
                               Thread.sleep(1000);
                               System.out.println("Thread still active");
                           } catch (InterruptedException ex) {
                           }
                       }
                       System.out.println("Thread terminating");
                   }
               };
           }
       }
       thread.start();
   }
   protected void pauseApp() {
       // Called from the timer task to
       // do whatever is necessary to 
       // pause the MIDlet.
       // Tell the background thread to stop.
       System.out.println("pauseApp called.");
       synchronized (this) {
           if (thread != null) {
               thread = null;
           }
       }
   }
   protected void destroyApp(boolean unconditional) 
                           throws MIDletStateChangeException {
       // Called to destroy the MIDlet.
       System.out.println("destroyApp called - unconditional = " 
                           + unconditional);
       if (thread != null) {
           Thread bgThread = thread;
           thread = null;      // Signal thread to die
           try {
               bgThread.join();
           } catch (InterruptedException ex) {
           }
       }
       stopTimer();
   }
   
   // Starts a timer to run a simple task
   private void startTimer() {
       
       // Create a task to be run
       task = new TimerTask() {
           private boolean isPaused;
           private int count;
       
           public void run() {
               // Pause or resume the MIDlet.
               System.out.println("Timer scheduled");
               if (count++ == 4) {
                   // Terminate the MIDlet
                   try {
                       ExampleMIDlet.this.destroyApp(true);
                   } catch (MIDletStateChangeException ex) {
                       // Ignore pleas for mercy!
                   }
                   ExampleMIDlet.this.notifyDestroyed();
                   return;
               }
               if (isPaused) {
                   System.out.println(">> Resuming MIDlet");
                   ExampleMIDlet.this.resumeRequest();
                   isPaused = false;
               } else {
                   System.out.println(">> Pausing MIDlet");
                   isPaused = true;
                   ExampleMIDlet.this.pauseApp();
                   ExampleMIDlet.this.notifyPaused();
               }                
           }
       };
       
       // Create a timer and schedule it to run
       timer = new Timer();
       timer.schedule(task, timerInterval, timerInterval); 
       System.out.println("Timer started.");
   }
   
   // Stops the timer
   private void stopTimer() {
       if (timer != null) {
           System.out.println("Stopping the timer");
           timer.cancel();
       }
   }

}


      </source>
   
  
 
  



Goodbye World

   <source lang="java">

/* MIDlet-Name: Hello World MIDlet-Version: 1.0 MIDlet-Vendor: Jim MIDlet-Description: My First MIDlet suite MIDlet-1: HelloWorld, /greeting/myLogo.png, greeting.HelloWorld MIDlet-2: GoodbyeWorld, /greeting/myLogo.png, greeting.GoodbyeWorld MIDlet-Jar-URL: HelloWorld.jar MIDlet-Jar-Size: 4048

  • /

import javax.microedition.lcdui.rumand; import javax.microedition.lcdui.rumandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.TextBox; import javax.microedition.midlet.MIDlet; public class GoodbyeWorld extends MIDlet implements CommandListener {

 private Display display;
 private TextBox textBox = new TextBox("Goodbye World", "My second MIDlet", 40, 0);
 private Command quitCommand = new Command("Quit", Command.SCREEN, 1);
 public void startApp() {
   display = Display.getDisplay(this);
   textBox.addCommand(quitCommand);
   textBox.setCommandListener(this);
   display.setCurrent(textBox);
 }
 public void pauseApp() {
 }
 public void destroyApp(boolean unconditional) {
 }
 public void commandAction(Command choice, Displayable displayable) {
   if (choice == quitCommand) {
     destroyApp(false);
     notifyDestroyed();
   }
 }

}


      </source>
   
  
 
  



Hello Midlet

   <source lang="java">

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class HelloMidlet extends MIDlet {

   // The display for this MIDlet
   private Display display;
   // TextBox to display text
   TextBox box = null;
   public HelloMidlet() {
   }
   public void startApp() {
       display = Display.getDisplay(this);
       box = new TextBox("Simple Example", "Hello World", 20, 0);
       display.setCurrent(box);
   }
   /**
    * Pause is a no-op since there are no background activities or
    * record stores that need to be closed.
    */
   public void pauseApp() {
   }
   /**
    * Destroy must cleanup everything not handled by the garbage collector.
    * In this case there is nothing to cleanup.
    */
   public void destroyApp(boolean unconditional) {
   }

}


      </source>
   
  
 
  



MIDlet lifecycle

   <source lang="java">

/*

* 
* Copyright (c) 2000 Sun Microsystems, Inc. All Rights Reserved.
*
* Author: Srikanth Raju
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information").  You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*/

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

* An example MIDlet with simple "Hello" text.
* Refer to the startApp, pauseApp, and destroyApp
* methods so see how each handles the requested transition.
*/

public class ConsoleHelloMIDlet extends MIDlet {

   /**
    * Start up the Hello MIDlet.  Just write some info
    */
   public void startApp() {
       System.out.println( "\nHello Camp" );
       pauseApp();
   }
   /**
    * Pause is a no-op since there are no background activities or
    * record stores that need to be closed.
    */
   public void pauseApp() {
      System.out.println( "In pauseApp... " );
      destroyApp( true );
   }
   /**
    * Destroy must cleanup everything not handled by the garbage collector.
    * In this case there is nothing to cleanup.
    */
   public void destroyApp(boolean unconditional) {
      System.out.println( "In destroyApp... " );
   }

}


      </source>
   
  
 
  



MIDlet State Transitions

   <source lang="java">

/*--------------------------------------------------

  • StateTransitions.java
  • Example from the book: Core J2ME Technology
  • Copyright John W. Muchow http://www.CoreJ2ME.ru
  • You may use/modify for any non-commercial purpose
  • -------------------------------------------------*/

import javax.microedition.midlet.*; public class StateTransitions extends MIDlet {

 public StateTransitions()
 {
   System.out.println("Inside constructor()");
 }
 // Required: called by application manager to start the MIDlet.
 public void startApp()
 {
   System.out.println("Inside startApp()");
 }
 // Required: called by application manager to pause the MIDlet.
 public void pauseApp()
 {
   System.out.println("Inside pauseApp()");
 }
 // Required: called by application manager before shutting down the MIDlet.
 public void destroyApp(boolean unconditional)
 {
   System.out.println("Inside destroyApp()");
 }

}


      </source>
   
  
 
  



Simple Midlet Demo

   <source lang="java">

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class MyMidlet extends MIDlet {

  public MyMidlet() { // constructor
  }
  public void startApp() {
     Canvas canvas = new MyCanvas();
     Display display = Display.getDisplay(this);
     display.setCurrent(canvas);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }

} class MyCanvas extends Canvas {

  public void paint(Graphics g) {
     g.setColor(255, 0, 0);
     g.fillRect(0, 0, getWidth(), getHeight());
     g.setColor(255, 255, 255);
     g.drawString("Hello World!", 0, 0, g.TOP | g.LEFT);
  }

}

      </source>
   
  
 
  



Welcome Back

   <source lang="java">

/*--------------------------------------------------

  • WelcomeBack.java
  • Example from the book: Core J2ME Technology
  • Copyright John W. Muchow http://www.CoreJ2ME.ru
  • You may use/modify for any non-commercial purpose
  • -------------------------------------------------*/

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class WelcomeBack extends MIDlet implements CommandListener {

 private Display display;      // Reference to Display object for this MIDlet
 private List lsMain;         // A List of items
 private Command cmExit;      // A Command to exit the MIDlet
 public WelcomeBack()
 {
   display = Display.getDisplay(this);
   
   cmExit = new Command("Exit", Command.SCREEN, 1);
   lsMain = new List("Welcome Back", Choice.IMPLICIT);
   lsMain.append("Core J2ME", null);
   lsMain.addCommand(cmExit);
   lsMain.setCommandListener(this);
 }
 // Called by application manager to start the MIDlet.
 public void startApp()
 {
   display.setCurrent(lsMain);
 }
 // A required method
 public void pauseApp()
 { }
 // A required method
 public void destroyApp(boolean unconditional)
 { }
 // Check to see if our Exit command was selected
 public void commandAction(Command c, Displayable s)
 {
   if (c == cmExit)
   {
     destroyApp(false);
     notifyDestroyed();
   } 
 }

}


      </source>
   
  
 
  



Welcome MIDlet

   <source lang="java">

/*--------------------------------------------------

  • WelcomeMIDlet.java
  • Example from the book: Core J2ME Technology
  • Copyright John W. Muchow http://www.CoreJ2ME.ru
  • You may use/modify for any non-commercial purpose
  • -------------------------------------------------*/

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class WelcomeMIDlet extends MIDlet implements CommandListener {

 private Display display;      // Reference to Display object for this MIDlet
 private TextBox tbMain;      // A Textbox to display a message
 private Command cmExit;      // A Command to exit the MIDlet
 public WelcomeMIDlet()
 {
   display = Display.getDisplay(this);
   
   cmExit = new Command("Exit", Command.SCREEN, 1);
   
   tbMain = new TextBox("Welcome", "Core J2ME", 50, 0);
   tbMain.addCommand(cmExit);
   tbMain.setCommandListener(this);
 }
 // Called by application manager to start the MIDlet.
 public void startApp()
 {
   display.setCurrent(tbMain);
 }
 // A required method
 public void pauseApp()
 { }
 // A required method
 public void destroyApp(boolean unconditional)
 { }
 // Check to see if our Exit command was selected
 public void commandAction(Command c, Displayable s)
 {
   if (c == cmExit)
   {
     destroyApp(false);
     notifyDestroyed();
   } 
 }

}


      </source>