For information about the design and functionality of the MIDlet, see section Design.
To create the MIDlet:
Create the SignedMIDlet.java
class file.
Import the required classes and packages.
import java.io.IOException; import java.io.InputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import javax.microedition.lcdui.*; import javax.microedition.midlet.*;
Set SignedMIDlet
to extend MIDlet
and implement Runnable
and CommandListener
. MIDlets use the Runnable
interface to execute threads and the CommandListener
interface to receive high-level UI events from the platform.
public class SignedMIDlet extends MIDlet implements Runnable, CommandListener {
Create the required
variables and the SignedMIDlet
class constructor.
private final TextField text = new TextField("", "", 256, TextField.ANY); private final Form form = new Form("HTTP Result"); private final Command exitCommand = new Command("Exit", Command.EXIT, 1); private final Command okCommand = new Command("Load", Command.OK, 1); public SignedMIDlet() { }
Define the mandatory lifecycle methods for starting, pausing, and destroying the MIDlet.
public void startApp() { if (Display.getDisplay(this).getCurrent() == null) { form.setCommandListener(this); } text.setString("http://www.w3.org"); form.addCommand(exitCommand); form.addCommand(okCommand); form.append(text); Display.getDisplay(this).setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { }
Use the run
method to read the URL and display the bytes read on
the screen. The run
method calls the protected open
method.
public void run() { // do an action that requires permission, e.g. HTTP connection try { HttpConnection connection = (HttpConnection) Connector.open(text.getString()); InputStream in = connection.openInputStream(); int counter = 0; int ch; while ((ch = in.read()) != -1) { counter++; } in.close(); connection.close(); form.append("Bytes read: " + counter+"\n"); } catch (IOException e) { showAlert("Network error"); } catch (SecurityException e) { showAlert("No permission to access the network"); } catch (Exception e) { showAlert("An error occurred"); } } private void showAlert(String text) { Alert alert = new Alert("Exception"); alert.setString(text); Display.getDisplay(this).setCurrent(alert); }
The MIDlet calls
the commandAction
method when a command has been
invoked. When the user selects Load, the MIDlet invokes the okCommand
and starts a new thread, and the Java Virtual
Machine automatically calls the run
method for the
new thread.
public void commandAction(Command command, Displayable displayable) { if (command == exitCommand) { notifyDestroyed(); } else if (command == okCommand) { new Thread(this).start(); } } }