|
3 Java手机与网络
3.1 J2ME手机对网络的支持
J2ME手机使用HTTP协议作为MIDP网络库的网络协议。HTTP是一个丰富而且被广泛使用的协议,可以在不同的无线网络中很简单地实现。MIDP设备的HTTP可以使用IP协议,例如TCP/IP或非IP协议像WAP或i-Mode来实现。MIDP网络API定义在javax.microedition.io.HttpConnection 中。这个接口扩展了javax.microedition.io.ContentConnection并且提供了附加的域和方法来解析URL、设置请求以及解析相应头。
3.2 J2ME手机对空间制图服务(WMS)导航图像(PNG 格式)数据的请求
以下代码仅演示J2ME手机对空间制图服务(WMS)数据请求核心的代码,空间制图服务(WMS)服务器,可以是任何符合OGC WMS标准的任何服务器(本文使用了Mapinfo MapXtreme 4.7提供的WMS服务)
package untitled9;
import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.io.*;
public class Untitled0
extends MIDlet
implements CommandListener, ItemStateListener {
Display display;
Canvas canvas0;
// Custom declaration code starts here
public Untitled0() {
display = Display.getDisplay(this);
canvas0 = new Canvas() {
public void paint(Graphics g) {
HttpConnection content = null;
byte[] contents = null;
try {
content = (HttpConnection)
Connector.open("http://localhost:8080/wmsserver111/servlet/wms?VERSION=1.1.1&SRS=epsg:4267&REQUEST=GetMap&LAYERS=Layers/Beijing/Road&STYLES=&BBOX=-180,-180,180,180&WIDTH=120&HEIGHT=120&FORMAT=image/png");
/************************************************************************
通过 Http 协议建立连接 content 对象,取得 GIS 图像数据文件的长度;然后,
按照该文件的长度构造缓冲区 kkk[];由 content 对象获取输入流,
将数据输入流与数据输入流连接,将 GIS 图像数据文件的数据读入缓冲区 kkk[],
由 kkk[]缓冲区构造静态 GIS 图像对象me=Image.createImage(kkk,0,kkk.length);
这样就可以构造出静态 GIS 图像,从而就可以使用任何绘图语句将图像在 J2ME 手机屏幕上。
图像的显示:建立一个画布 Canvas,在 Canvas 的 paint 事件中,加入如下代码:
g.drawImage(me,0, 0, Graphics.LEFT| Graphics.TOP);
*************************************************************************/
try {
DataInputStream _in = new DataInputStream(content.openInputStream());
_in.available();
int _length = (int) content.getLength();
if (_length < 1) {
_length = _in.available();
System.out.println(_length);
}
contents = new byte[_length];
_in.readFully(contents);
_in.close();
System.out.println(contents.length);
Image img = Image.createImage(contents, 0, contents.length - 1);
g.drawImage(img, 0, 0, g.LEFT | g.TOP);
}
catch (IOException except) {
except.printStackTrace();
}
}
catch (IOException excpt0) {
excpt0.printStackTrace();
}
}
{
this.addCommand(new Command("command1",
Command.SCREEN, 1));
setCommandListener(Untitled0.this);
}
};
// Custom constructor code starts here
}
public void startApp()
throws MIDletStateChangeException
{
display.setCurrent(canvas0);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) throws
MIDletStateChangeException {
}
public void itemStateChanged(Item item) {
}
public void commandAction(Command c, Displayable d) {
if (c.getLabel().equals("command1") && d == canvas0) {
}
}
}
|
|