J2ME蓝牙实战入实例代码和参考资料可实现两人或多人通过蓝牙通信的游戏对弈Sun Java Wireless Toolkit.docx
《J2ME蓝牙实战入实例代码和参考资料可实现两人或多人通过蓝牙通信的游戏对弈Sun Java Wireless Toolkit.docx》由会员分享,可在线阅读,更多相关《J2ME蓝牙实战入实例代码和参考资料可实现两人或多人通过蓝牙通信的游戏对弈Sun Java Wireless Toolkit.docx(35页珍藏版)》请在冰豆网上搜索。

J2ME蓝牙实战入实例代码和参考资料可实现两人或多人通过蓝牙通信的游戏对弈SunJavaWirelessToolkit
SunJavaWirelessToolkitforCLDC
sun_java_wireless_toolkit-2_5_2-ml-windows.exe
SunJavaWirelessToolkit(先前称为J2MEWirelessToolkit,WTK)是一组用于创建Java应用程序的工具,这些应用程序可在符合JavaTechnologyfortheWirelessIndustry(JTWI)(JSR185)规范和MobileServiceArchitecture(MSA)(JSR248)规范的设备上运行。
它包含生成工具、实用程序和设备仿真器。
WTK2.5.2的新增功能有哪些?
改进对多用户环境的支持
Ubuntulinux版本是根据glibc2.3库构建的,可以为其他Linux发行版提供未经测试的支持
您也可以开发针对CLDC1.0和MIDP1.0的应用程序。
SunJavaWirelessToolkit2.5.2包括SunJavaWirelessToolkit2.2版、SunJavaWirelessToolkit2.5版和SunJavaWirelessToolkit2.5.1版中的所有高级开发功能,例如MIDlet签名、证书管理、集成的无线协议(OTA)仿真、推送注册表仿真等更多功能。
此版本的SunJavaWirelessToolkit包括诺基亚的ScalableNetworkApplicationPackage(SNAP)MobileAPI和SNAPMobile样例应用程序,作为工具包外部API功能的一部分。
SNAPMobile是客户机软件和服务器基础结构的组合,它支持创建联网的社区类多玩家游戏。
有关更多信息,请参阅SNAPMobileWeb站点Mobile的仿真环境、开发资源以及各种支持可通过获得。
有关更多信息,请参见SNAPMobile仿真环境安装。
J2ME蓝牙实战入门
陈万飞,网名Jagie,培训师,爱好java技术.可通过chen_cwf@与他联系
2007年08月02日
概述
目前,很多手机已经具备了蓝牙功能。
虽然MIDP2.0没有包括蓝牙API,但是JCP定义了JSR82,JavaAPIsforBluetoothWirelessTechnology(JABWT).这是一个可选API,很多支持MIDP2.0的手机已经实现了,比如Nokia6600,Nokia6670,Nokia7610等等。
对于一个开发者来说,如果目标平台支持JSR82的话,在制作联网对战类型游戏或者应用的时候,蓝牙是一个相当不错的选择。
本文给出了一个最简单的蓝牙应用的J2ME程序,用以帮助开发者快速的掌握JSR82。
该程序分别在2台蓝牙设备上安装后,一台设备作为服务端先运行,一台设备作为客户端后运行。
在服务端上我们发布了一个服务,该服务的功能是把客户端发过来的字符串转变为大写字符串。
客户端起动并搜索到服务端的服务后,我们就可以从客户端的输入框里输入任意的字符串,发送到服务端去,同时观察服务端的反馈结果。
本文并不具体讲述蓝牙的运行机制和JSR82的API结构,关于这些知识点,请参考本文的参考资料一节,这些参考资料会给你一个权威的精确的解释。
实例代码
该程序包括3个java文件。
一个是MIDlet,另外2个为服务端GUI和客户端GUI。
该程序已经在wtk22模拟器和Nokia6600,Nokia6670两款手机上测试通过。
StupidBTMIDlet.java
importjavax.microedition.lcdui.Alert;
importjavax.microedition.lcdui.AlertType;
importjavax.microedition.lcdui.Command;
importjavax.microedition.lcdui.CommandListener;
importjavax.microedition.lcdui.Display;
importjavax.microedition.lcdui.Displayable;
importjavax.microedition.lcdui.List;
importjavax.microedition.midlet.MIDlet;
importjavax.microedition.midlet.MIDletStateChangeException;
/**
*@authorJagie
*
*MIDlet
*/
publicclassStupidBTMIDletextendsMIDletimplementsCommandListener{
Listlist;
ServerBoxsb;
ClientBoxcb;
/*
*(non-Javadoc)
*
*@seejavax.microedition.midlet.MIDlet#startApp()
*/
protectedvoidstartApp()throwsMIDletStateChangeException{
list=newList("傻瓜蓝牙入门",List.IMPLICIT);
list.append("Client",null);
list.append("Server",null);
list.setCommandListener(this);
Display.getDisplay(this).setCurrent(list);
}
/**
*debug方法
*@params要显示的字串
*/
publicvoidshowString(java/lang/String.java.html"target="_blank">Strings){
Displayabledp=Display.getDisplay(this).getCurrent();
Alertal=newAlert(null,s,null,AlertType.INFO);
al.setTimeout(2000);
Display.getDisplay(this).setCurrent(al,dp);
}
/**
*显示主菜单
*
*/
publicvoidshowMainMenu(){
Display.getDisplay(this).setCurrent(list);
}
protectedvoidpauseApp(){
//TODOAuto-generatedmethodstub
}
publicvoidcommandAction(Commandcom,Displayabledisp){
if(com==List.SELECT_COMMAND){
Listlist=(List)disp;
intindex=list.getSelectedIndex();
if(index==1){
if(sb==null){
sb=newServerBox(this);
}
sb.setString(null);
Display.getDisplay(this).setCurrent(sb);
}else{
//每次都生成新的客户端实例
cb=null;
java/lang/System.java.html"target="_blank">System.gc();
cb=newClientBox(this);
Display.getDisplay(this).setCurrent(cb);
}
}
}
protectedvoiddestroyApp(booleanarg0)throwsMIDletStateChangeException{
//TODOAuto-generatedmethodstub
}
}
ClientBox.java
importjava.io.java/io/DataInputStream.java.html"target="_blank">DataInputStream;
importjava.io.java/io/DataOutputStream.java.html"target="_blank">DataOutputStream;
importjava.io.java/io/IOException.java.html"target="_blank">IOException;
importjava.util.java/util/Vector.java.html"target="_blank">Vector;
importjavax.microedition.io.Connector;
importjavax.microedition.io.StreamConnection;
importjavax.microedition.lcdui.Command;
importjavax.microedition.lcdui.CommandListener;
importjavax.microedition.lcdui.Displayable;
importjavax.microedition.lcdui.Form;
importjavax.microedition.lcdui.Gauge;
importjavax.microedition.lcdui.StringItem;
importjavax.microedition.lcdui.TextField;
//jsr082API
importjavax.bluetooth.BluetoothStateException;
importjavax.bluetooth.DeviceClass;
importjavax.bluetooth.DiscoveryAgent;
importjavax.bluetooth.DiscoveryListener;
importjavax.bluetooth.LocalDevice;
importjavax.bluetooth.RemoteDevice;
importjavax.bluetooth.ServiceRecord;
importjavax.bluetooth.UUID;
/**
*客户端GUI
*@authorJagie
*
*TODOTochangethetemplateforthisgeneratedtypecommentgoto
*Window-Preferences-Java-CodeStyle-CodeTemplates
*/
publicclassClientBoxextendsFormimplementsjava/lang/Runnable.java.html"target="_blank">Runnable,CommandListener,
DiscoveryListener{
//字串输入框
TextFieldinput=newTextField(null,"",50,TextField.ANY);
//loger
StringItemresult=newStringItem("结果:
","");
privateDiscoveryAgentdiscoveryAgent;
privateUUID[]uuidSet;
//响应服务的UUID
privatestaticfinalUUIDECHO_SERVER_UUID=newUUID(
"F0E0D0C0B0A000908070605040302010",false);
//设备集合
java/util/Vector.java.html"target="_blank">Vectordevices=newjava/util/Vector.java.html"target="_blank">Vector();
//服务集合
java/util/Vector.java.html"target="_blank">Vectorrecords=newjava/util/Vector.java.html"target="_blank">Vector();
//服务搜索的事务id集合
int[]transIDs;
StupidBTMIDletmidlet;
publicClientBox(StupidBTMIDletmidlet){
super("");
this.midlet=midlet;
this.append(result);
this.addCommand(newCommand("取消",Command.CANCEL,1));
this.setCommandListener(this);
newjava/lang/Thread.java.html"target="_blank">Thread(this).start();
}
publicvoidcommandAction(Commandarg0,Displayablearg1){
if(arg0.getCommandType()==Command.CANCEL){
midlet.showMainMenu();
}else{
//匿名内部Thread,访问远程服务。
java/lang/Thread.java.html"target="_blank">ThreadfetchThread=newjava/lang/Thread.java.html"target="_blank">Thread(){
publicvoidrun(){
for(inti=0;iServiceRecordsr=(ServiceRecord)records.elementAt(i);
if(accessService(sr)){
//访问到一个可用的服务即可
break;
}
}
}
};
fetchThread.start();
}
}
privatebooleanaccessService(ServiceRecordsr){
booleanresult=false;
try{
java/lang/String.java.html"target="_blank">Stringurl=sr.getConnectionURL(
ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
StreamConnectionconn=(StreamConnection)Connector.open(url);
java/io/DataOutputStream.java.html"target="_blank">DataOutputStreamdos=conn.openDataOutputStream();
dos.writeUTF(input.getString());
dos.close();
java/io/DataInputStream.java.html"target="_blank">DataInputStreamdis=conn.openDataInputStream();
java/lang/String.java.html"target="_blank">Stringecho=dis.readUTF();
dis.close();
showInfo("反馈结果是:
"+echo);
result=true;
}catch(java/io/IOException.java.html"target="_blank">IOExceptione){
}
returnresult;
}
publicsynchronizedvoidrun(){
//发现设备和服务的过程中,给用户以Gauge
Gaugeg=newGauge(null,false,Gauge.INDEFINITE,Gauge.CONTINUOUS_RUNNING);
this.append(g);
showInfo("蓝牙初始化...");
booleanisBTReady=false;
try{
LocalDevicelocalDevice=LocalDevice.getLocalDevice();
discoveryAgent=localDevice.getDiscoveryAgent();
isBTReady=true;
}catch(java/lang/Exception.java.html"target="_blank">Exceptione){
e.printStackTrace();
}
if(!
isBTReady){
showInfo("蓝牙不可用");
//删除Gauge
this.delete
(1);
return;
}
uuidSet=newUUID[2];
//标志我们的响应服务的UUID集合
uuidSet[0]=newUUID(0x1101);
uuidSet[1]=ECHO_SERVER_UUID;
try{
discoveryAgent.startInquiry(DiscoveryAgent.GIAC,this);
}catch(BluetoothStateExceptione){
}
try{
//阻塞,由inquiryCompleted()回调方法唤醒
wait();
}catch(java/lang/InterruptedException.java.html"target="_blank">InterruptedExceptione1){
e1.printStackTrace();
}
showInfo("设备搜索完毕,共找到"+devices.size()+"个设备,开始搜索服务");
transIDs=newint[devices.size()];
for(inti=0;iRemoteDevicerd=(RemoteDevice)devices.elementAt(i);
try{
//记录每一次服务搜索的事务id
transIDs[i]=discoveryAgent.searchServices(null,uuidSet,
rd,this);
}catch(BluetoothStateExceptione){
continue;
}
}
try{
//阻塞,由serviceSearchCompleted()回调方法在所有设备都搜索完的情况下唤醒
wait();
}catch(java/lang/InterruptedException.java.html"target="_blank">InterruptedExceptione1){
e1.printStackTrace();
}
showInfo("服务搜索完毕,共找到"+records.size()+"个服务,准备发送请求");
if(records.size()>0){
this.append(input);
this.addCommand(newCommand("发送",Command.OK,0));
}
//删除Gauge
this.delete
(1);
}
/**
*debug
*@params
*/
privatevoidshowInfo(java/lang/String.java.html"target="_blank">Strings){
java/lang/StringBuffer.java.html"target="_blank">StringBuffersb=newjava/lang/StringBuffer.java.html"target="_blank">StringBuffer(result.getText());
if(sb.length()>0){
sb.append("\n");
}
sb.append(s);
result.setText(sb.toString());
}
/**
*回调方法
*/
publicvoiddeviceDiscovered(RemoteDevicebtDevice,DeviceClasscod){
if(devices.indexOf(btDevice)==-1){
devices.addElement(btDevice);
}
}
/**
*回调方法,唤醒初始化线程
*/
publicvoidinquiryCompleted(intdiscType){
synchronized(this){
notify();
}
}
/**
*回调方