How to use J2ME

xiaoxiao2021-03-06  43

J2ME I / O and Network: Overview Java 2 platform, Pocket Edition (Java 2 Platform, Micro Edition (J2ME) provides networking features available on the network to mobile space. It is possible to get real-time stock quotes or the latest loan exchange rates in mobile phones or palms.

The networked features of the Mobile Information Framework (MIDP) in javax.microedition.IO, MIDP is a platform for developing mobile device applications. On the other hand, Java.IO package provides MIDP to provide input / output (INPUT / OUTPUT (I / O)) function. Its individual classes and interfaces provide system input and output for data streams. This J2ME package is a subset of Java 2 platform, standard version (Java 2 Platform, Standard Edition (J2SE)) java.io package, which handles low-level data I / O.

The most critical aspect of J2ME network connectivity is the communication between the mobile device and the web server. This kind of communication is essentially a client / server mechanism, with mobile devices act as a web client's role and capacity to establish an interface with enterprise systems, databases, corporate internal networks and Internet.

J2ME networking activities can be divided into many types in accordance with the communication protocol. We will discuss each category in the following sections.

Low-level IP network

This category involves sockets, datagrams, serial ports, and file I / O communications. Communication based on socket follows the connected TCP / IP protocol. On the other hand, the data report-based communication follows the unconnected UDP / IP protocol. UDP provides the application with a method of sending a packaged original IP datagram that does not have to establish a connection. The connection-oriented protocol requires the source address and destination address, which is different from this, and the datagram only needs the destination address. Below is a URI for the datagram connection to accept the data report in a certain port:

DataGram: //: 1234

Here is a URI that the datagram connection is used to send the datagram to the server at a port:

DataGram: //123.456.789.12: 1234

Low level IP networks can also handle file I / O and allow MIDlet registration to network access to local serial ports.

Security network

The security network in J2ME involves some additional interfaces provided to secure communication with web-based network services. These security interfaces are provided by HTTPS and SSL / TLS protocols on IP networks.

HTTP network

Communication is based on HTTP (Hypertext Transfer Protocol, Hyper Text Transfer Protocol) between the mobile device and the web server. HTTP is a connection-oriented request-response (REQEST-RESPONSE) protocol, in which each parameter must be set before sending requests. Figure 1 illustrates the communication mechanism between the mobile device and the web server.

Figure 1. Connection mechanism between mobile devices and web servers

Connection frame

The J2ME network is designed to deal with different needs of the wide spectrum of mobile devices. At the same time, the networked system must be devices. In order to cope with these requirements, the J2ME network introduces the concept of the General Connection Framework.

The idea of ​​the general connection framework is to define some universal abstraction of the network and file I / O in the form of a Java interface. This architecture has widely supported various handheld devices, and the actual implementation of these interfaces is left to each device manufacturer. Equipment manufacturers can select which interface to implement in its specific MIDP according to the actual functionality of its device. The general aspects defined by the Java interface are divided into the following forms of basic communication types: 1. Basic serial input (defined by javax.microedition.io.inputConnection)

2. Basic serial output (defined by javax.microedition.io.OutputConnection)

3. Data report communication (defined by javax.microedition.io.DatagramConnection)

4. Socket communication notification mechanism for client-server (Client-Server) (defined by javax.microedition.io.StreamConnectionNotifier)

5. Basic HTTP communication with the web server (defined by javax.microedition.io.httpConnection)

URL processing in J2ME

The URL process in J2ME involves opens a connection from the mobile device to the web server and processes data I / O between the mobile device to the web server. This process occurs in the following stage:

1. Establish (SETUP), which is not established to the server. The mobile device prepares a bunch of request parameters and is ready to accept and explain the subsequent response.

2. Connected (Connected), the connection has been established, the request parameter has been sent and is expected to respond.

3. Closed (closed), at which point the connection has been turned off.

J2ME defines the Javax.microedition.io.Connector class, which contains each static (STIC) method for creating all connection objects. This task is done by dynamically identifying a class based on the protocol of the platform name and the requested connection. In URL processing, Connector.Open () is used to open the URL; it returns an HTTPConnection object. The string parameter of the Connector.Open () method is a valid URL. The URL string differs depending on the communication protocol. The following list 1 is demonstrated in Listing 5.

Listing 1. Calling HTTP-based communication

Connection conn = connector.open ("http://www.yahoo.com");

Listing 2. Calling stream-based socket communication

Connection conn = connector.open ("socket: // localhost: 9000);

Listing 3. Calling a dataginary socket communication

Connection conn = connector.open ("DataGram: //: 9000);

Listing 4. Call serial communication

Connection conn = connector.open ("Comm: 0; baudrate = 9000);

Listing 5. Calling file I / O communication

Connection conn = connector.open ("file: //myfile.dat);

The Connector.Open () method can also accept access modes (values ​​for READ, WRITE, and READ_WRITE) and a logo used to indicate the caller to get the timeout notification. In a secure network, when the https: // Connection string is accessed, Connector.Open () returns httpsconnection. When the SSL: / / Connection string is accessed, Connector.Open () will return SecureConnection. No matter which type of URL is used, call connector.Open () opens a stream of byte input from the Connection to Java.Io.inputStream. This method uses to read each character of the file, always read the end of the file (marked with -1). If an exception is thrown, the connection and flow will be turned off. Similarly, in order to perform output, Java.io.OutputStream representing byte output stream will be opened from Connection.

InputStream and OutputStream are corresponding to java.io.DataInputStream and Java.io.DataoutputStream. DataInputStream allows the application to read the basic Java data type from the underlying input stream from the underlying manner. Java.io.DataOutputStream allows applications to write basic Java data types to output streams in portable ways. Listing 6 illustrates how to use HTTPConnection from the URL input data.

Listing 6. Enter data from URL using HTTPConnection

String getViahttpConnection (String Url) throws oException {

HttpConnection C = NULL;

InputStream IS = NULL;

StringBuffer str = new stringbuffer ();

Try {

C = (httpConnection) Connector.Open (URL);

// Getting the InputStream Will Open THE Connection

// and read the http headers. They area stored unsil

// Requester.

IS = C.OpenInputStream ();

// Get the length and process the data

INT LEN = (int) c.getlength ();

int CH;

While ((ch = is.read ())! = -1) {

Str.Append ((char) CH);

}

} finally {

IF (is! = null)

Is.close ();

IF (c! = null)

C. close ();

}

A loan currency exchange application

We will explain the concepts outlined so far through a loan currency exchange application, which will display the latest exchange rate between USD (U.S. Dollar, USD) and British Pound, GBP. This app also displays information related to the current date and current time.

The UI of this application consists of a form (Form) and an exit command that embeds the StringItem representing a string that only the string is displayed, and the exit command is used to complete the call to exit. Once the application is started, the URL request is ready. Basic currency symbols are provided to the request. Next, we need to open a mobile device and the URL connection between the web server. Open an HTTPConnection and create an InputStream for the data input. The data obtained is a character stream that is attached to the string. The resulting String represents the HTML output. Since the browser on our mobile device cannot display HTML, we will parse the HTML String to get currency values ​​and any related information. Our program will search for a specific mode in the HTML String, namedGBP. Once the location of this mode is determined, the search finds the decimal value. When the position of the decimal point is obtained, each numeric value will be retrieved and arranged in an appropriate order, thereby acquiring the currency value. Listing 7 illustrates how to obtain a currency value.

Listing 7. Retrieving currency values

String retval = "";

INT DEC = 0;

Int index = str.indexof ("USDGBP");

IF (INDEX! = -1)

Str = str.substring (index, str.length ());

IF ((DEC = str .indexof ("."))! = -1) && (! (str.endswith (")))))

&& Character.Indigit (Str.Charat (DEC 1))))

{

String front = ""

INT FIND = DEC-1;

While (character.isdigit (str.charat (find)))

{

Front = str.charat (find);

Find-;

}

Retval = New StringBuffer (Front) .reverse (). Tostring ();

RetVal = "."

String back = "";

INT BIND = DEC 4;

While (character.isdigit (str.charat (bind)))

{

BACK = str.charat (bind);

Bind-;

}

Retval = new stringbuffer (back) .reverse (). TOSTRING ();

}

Related information is also obtained by looking for some specific string modes. Once the location of the data is in the HTML String, an offset will be applied to obtain the date and time. This information is attached to the string mode originally used for search. Listing 8 illustrates how to obtain related information, inventory 9 includes all code for currency exchange applications.

Listing 8. Search related information

// get the time of currency Exchange and related information

INT TIMEINDEX = Str.Indexof ("U.S. Markets Closed.");

String rettime = "";

IF (TimeIndex! = -1)

{

Rettime = Str.Substring (TimeIndex-34, TimeIndex);

Rettime = "u.s. markets closed";

Listing 9. Complete currency exchange example

Import javax.microedition.midlet. *;

Import javax.microedition.lcdui. *;

Import javax.microedition.io. *;

Import java.io. *;

Import java.lang. *;

Import java.util. *;

// a First Midlet with Simple Text and A Few Commands.

Public Class CurrencyExchange Extends MIDLET

Implements commandListener {

// the EXIT COMMANDS

Private Command EXITCOMMAND;

// the display for this MIDLET

Private display display;

Form Displayform;

Public currencyexchange () {

Display = display.getdisplay (this);

EXITCOMMAND =

New Command ("exit", command.screen, 1);

}

// start the midlet by create the form and

// Associating The EXIT Command and Listener.

Public void startapp () {

DisplayForm = New form ("Exchange Rate");

DisplayForm.Addcommand (exitcommand);

Displayform.SetCommandListener (this);

Try

{

String result = getViahttpConnection

("http://finance.yahoo.com/m5?a=1&s=usd&t=gbp");

DisplayForm.Append (" result);

}

Catch (Exception EXC)

{

Exc.printStackTrace ();

}

Display.SetCurrent (DisplayForm);

}

// Pause is a no-op Because there is no background

// Activities or Record Stores to be closed.

Public void pauseapp () {}

// Destroy Must Cleanup Everything Not Handled

// by The Garbage Collector.

// in this case there is nothing to clean.

Public void destroyApp (boolean unconditional) {}

// Respond to commands. Here We are Only Implementing

// the exit command. in the exit command, Cleanup and

// Notify That The Midlet Has Been Destroyed.

Public void CommandAction

Command C, Displayable S) {

IF (c == EXITCOMMAND) {

DESTROYAPP (FALSE);

NotifyDestroyed ();

}

}

String Parse (String STR)

{

// get the time of currency Exchange and related information

INT TIMEINDEX = Str.Indexof ("U.S. Markets Closed.");

String rettime = "";

IF (TimeIndex! = -1)

{

Rettime = Str.Substring (TimeIndex-34, TimeIndex);

Rettime = "u.s. markets closed";

}

String retval = "";

INT DEC = 0;

Int index = str.indexof ("USDGBP");

IF (INDEX! = -1)

Str = str.substring (index, str.length ());

IF ((DEC = str .indexof ("."))! = -1) && (! (str.endswith (")))))

&& Character.Indigit (Str.Charat (DEC 1))))

{

String front = ""

INT FIND = DEC-1;

While (character.isdigit (str.charat (find)))

{

Front = str.charat (find);

Find-;

}

Retval = New StringBuffer (Front) .reverse (). Tostring ();

RetVal = "."

String back = "";

INT BIND = DEC 4;

While (character.isdigit (str.charat (bind)))

{

BACK = str.charat (bind);

Bind-;

}

Retval = new stringbuffer (back) .reverse (). TOSTRING ();

}

System.out.println (RetVal);

Return "USD / GBP" RetVal "AT" rettime;

}

String getViahttpConnection (String Url) throws oException {

HttpConnection C = NULL;

InputStream IS = NULL;

StringBuffer str = new stringbuffer ();

Try {

C = (httpConnection) Connector.Open (URL);

// Get the contenttype

String type = c.gettype ();

// Getting the InputStream Will Open THE Connection

// and read the http headers. They area stored unsil

// Requester.

IS = C.OpenInputStream ();

// Get the length and process the data

INT LEN = (int) c.getlength ();

int CH;

While ((ch = is.read ())! = -1) {str.append ((char) ch);

}

} finally {

IF (is! = null)

Is.close ();

IF (c! = null)

C. close ();

}

// Before returning, the resultant string sales be pased to get Exchange Rate

String Val = parse (str.tostring ());

System.out.println (VAL);

Return Val;

}

}

The currency value and other related information have appeared on the user interface of the mobile device.

J2ME has a unique way to process data input / output in a constraint environment. With this feature, supporting Java mobile accessories is no longer a simple communication device, but can act as a micro browser device, which can provide important information in mobile. (T117)

转载请注明原文地址:https://www.9cbs.com/read-73003.html

New Post(0)