1、BlueToothMIDlet类
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class BlueToothMIDlet extends MIDlet implements CommandListener {
private static BlueToothMIDlet instance;
private BlueToothClient blueClientBox = null; // 客户端实例
private BlueToothServer blueServerBox = null; // 服务端实例
private List list = null; // 列表实例
public BlueToothMIDlet() {
instance = this;
}
public void startApp() {
list = new List("蓝牙聊天实例", List.IMPLICIT);
list.append("客户端", null);
list.append("服务端", null);
list.setCommandListener(this);
Display.getDisplay(this).setCurrent(list);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public static void quitApp() {
instance.destroyApp(true);
instance.notifyDestroyed();
instance = null;
}
public void commandAction(Command command, Displayable displayable) {
if (command == List.SELECT_COMMAND) {
if (list.getSelectedIndex() == 0) { // 运行客户端
blueClientBox = new BlueToothClient();
Display.getDisplay(this).setCurrent(blueClientBox);
} else if (list.getSelectedIndex() == 1) { // 运行服务端
blueServerBox = new BlueToothServer();
Display.getDisplay(this).setCurrent(blueServerBox);
}
}
}
}
2、BlueToothServer类
import javax.microedition.lcdui.*;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.io.StreamConnectionNotifier;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import java.io.*;
import java.util.Vector;
/**
* 设置一个蓝牙服务器
* 要设置一个能提供消费服务的蓝牙服务器,将有四个主要步骤:
* 1.创建一个你想要提供的可消费服务的服务记录,
* 2.增加一个新的服务记录到服务发现数据库,
* 3.注册服务。
* 4.等候客户端的引入连接。
* 两个有重要意义的相关操作:
* 1.修改服务记录,如果服务属性能使客户端可视需要改变;
* 2.当所有的都做了,从SDDB移除服务记录。
*/
public class BlueToothServer extends MyForm implements Runnable, CommandListener {
// 本地设备类实例
private LocalDevice localDevice = null;
// 服务记录实例
private ServiceRecord serviceRecord = null;
// 服务通告实例
private StreamConnectionNotifier notifier = null;
// 蓝牙服务url
private String url = "btspp://localhost:F0E0D0C0B0A000908070605040302010;name=BTServer;authorize=false";
private SenderMSG sender;
// 连接容器
public Vector connect = null;
public BlueToothServer() {
super("服务器端");
sender = new SenderMSG(this);
this.addCommand(comBack);
this.append(stringItem);
this.setCommandListener(this);
connect = new Vector();
new Thread(this).start();
}
public void commandAction(Command command, Displayable displayable) {
if (command.getCommandType() == Command.EXIT) {
sender.clear();
BlueToothMIDlet.quitApp();
} else if (command.getCommandType() == Command.OK) {
sender.blSend = true;
Thread fetchThread = new Thread() {
public void run() {
sender.sendMessage();
}
};
fetchThread.start();
}
}
public void run() {
try {
// 得到本地设备
this.localDevice = LocalDevice.getLocalDevice();
this.localDevice.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException ex) {
ex.printStackTrace();
}
try {
// 获得客户端连接通告
notifier = (StreamConnectionNotifier) Connector.open(this.url);
stringItem.setText("初始化成功等待连接!");
} catch (IOException ex1) {
ex1.printStackTrace();
}
// 获得服务记录
serviceRecord = localDevice.getRecord(notifier);
try {
// 从通告获得远端蓝牙设备的连接
sender.streamConnection = notifier.acceptAndOpen();
sender.init();
this.append(textField);
this.addCommand(comOk);
stringItem.setText("连接成功!");
} catch (IOException ex2) {
ex2.printStackTrace();
}
while (true) {
if (sender.blSend) {
try {
synchronized (this) {
wait();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
sender.receiveMessage();
}
}
}
3、BlueToothClient类
import javax.microedition.lcdui.*;
import javax.bluetooth.*;
import java.util.Vector;
import javax.microedition.io.*;
import java.io.*;
public class BlueToothClient extends MyForm implements Runnable, CommandListener,DiscoveryListener
{
//设备发现代理
private DiscoveryAgent discoverAgent = null;
//本地蓝牙设备实例
private LocalDevice localDevice = null;
//远端设备实例
private RemoteDevice remoteDevice = null;
//全球唯一标识符
private UUID[] uuid = null;
//服务记录实例
private ServiceRecord serviceRecord = null;
//设备容器
private Vector device = null;
//服务容器
private Vector service = null;
private SenderMSG sender;
//用于蓝牙连接的url
private String url = null;
public BlueToothClient()
{
super("客户端");
sender = new SenderMSG(this);
this.append(stringItem);
this.append(textField);
this.addCommand(comOk);
this.addCommand(comBack);
this.setCommandListener(this);
this.device = new Vector();
this.service = new Vector();
new Thread(this).start();
}
public void commandAction(Command command, Displayable displayable)
{
if (command.getCommandType() == Command.EXIT)
{
sender.clear();
discoverAgent.cancelInquiry(this);
discoverAgent.cancelServiceSearch(0);
BlueToothMIDlet.quitApp();
}
else if(command.getCommandType() == Command.OK)
{
sender.blSend = true;
Thread fetchThread = new Thread()
{
public void run()
{
//发送消息
sender.sendMessage();
}
};
fetchThread.start();
}
}
public void run()
{
//midp2.0进度条(持续动画状态)
Gauge gauge = new Gauge(null,false,Gauge.INDEFINITE,Gauge.CONTINUOUS_RUNNING);
this.append(gauge);
//开始搜索服务端蓝牙设备
stringItem.setText("开始搜索蓝牙设备...");
startSearchDevices();
try
{
synchronized(this)
{
wait();
}
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
stringItem.setText("共找到:"+device.size()+"个蓝牙设备开始搜索服务...");
//开始搜索远端设备提供的服务
startSearchServices();
try
{
synchronized(this)
{
wait();
}
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
stringItem.setText("共找到:"+service.size()+"个服务开始发送信息。");
url = serviceRecord.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
try
{
sender.streamConnection = (StreamConnection)Connector.open(url);
sender.init();
}
catch (IOException ex1)
{
ex1.printStackTrace();
}
//删除进度条
this.delete(2);
while(true)
{
if(sender.blSend)
{
try
{
synchronized(this)
{
wait();
}
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
sender.receiveMessage();
}
}
/**
* 蓝牙设备发现
*/
private void startSearchDevices()
{
try
{
//获得本地设备
localDevice = LocalDevice.getLocalDevice();
//获得发现代理
discoverAgent = localDevice.getDiscoveryAgent();
discoverAgent.startInquiry(DiscoveryAgent.GIAC,this);
}
catch (BluetoothStateException ex)
{
ex.printStackTrace();
}
}
/**
* 远端设备服务发现
*/
private void startSearchServices()
{
uuid = new UUID[2];
uuid[0] = new UUID(0x1101);
uuid[1] = new UUID("F0E0D0C0B0A000908070605040302010",false);
for(int i = 0; i<device.size(); i++)
{//取出已经搜到的远端设备
remoteDevice = (RemoteDevice)device.elementAt(i);
try
{//搜索该设备上的服务
discoverAgent.searchServices(null, uuid, remoteDevice, this);
}
catch (BluetoothStateException ex)
{
ex.printStackTrace();
}
}
}
/**
* 设备发现过程中的回调(用来查找每一个可用的设备)
* @param remoteDevice RemoteDevice
* @param deviceClass DeviceClass
*/
public void deviceDiscovered(RemoteDevice remoteDevice,DeviceClass deviceClass)
{
if(device.indexOf(remoteDevice) == -1)
{
device.addElement(remoteDevice);
}
}
/**
* 设备发现完成回调(用来标识设备查找是否完成)
* @param _int int
*/
public void inquiryCompleted(int _int)
{
synchronized (this)
{
notify();
}
}
/**
* 服务发现回调(用来发现远端设备上的可用服务)
* @param _int int
* @param serviceRecordArray ServiceRecord[]
*/
public void servicesDiscovered(int _int, ServiceRecord[] serviceRecordArray)
{
for (int i = 0; i < serviceRecordArray.length; i++)
{
service.addElement(serviceRecordArray[i]);
serviceRecord = serviceRecordArray[i];
}
}
/**
* 服务发现回调(用来标识服务搜索是否完成)
* @param _int int
* @param _int1 int
*/
public void serviceSearchCompleted(int _int, int _int1)
{
synchronized (this)
{
notify();
}
}
}
5、 MyForm类
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
public class MyForm extends Form {
// 发送按钮
public Command comOk = null;
// 返回按钮
public Command comBack = null;
public TextField textField = null;
public StringItem stringItem = null;
public MyForm(String title) {
super(title);
comOk = new Command("发送", Command.OK, 1);
comBack = new Command("退出", Command.EXIT, 2);
}
}
6、 SenderMSG类
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
public class SenderMSG {
// 连接实例
public StreamConnection streamConnection = null;
// 输出数据流
private DataOutputStream dataOutputStream = null;
// 输入数据流
private DataInputStream dataInputStream = null;
//接收阻塞标记
public boolean blSend = false;
private MyForm form;
public SenderMSG(Form f){
form = (MyForm)f;
form.textField = new TextField("输入:", "", 50, TextField.ANY);
form.stringItem = new StringItem("反馈:", "");
}
public void init(){
try {
dataOutputStream = streamConnection.openDataOutputStream();
dataInputStream = streamConnection.openDataInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发送消息
*/
public void sendMessage() {
String text = form.textField.getString();
// System.out.println("send text="+text);
if(text==null||text.length()==0)
return;
try {
dataOutputStream.write(text.getBytes());
dataOutputStream.write("/r/n".getBytes());
} catch (IOException ex) {
ex.printStackTrace();
}
blSend = false;
synchronized (this) {
notify();
}
}
/**
* 接受消息
* @return
*/
public boolean receiveMessage() {
try {
if (streamConnection!=null&&dataInputStream != null) {
StringBuffer sb = new StringBuffer();
int c = 0;
while (((c = dataInputStream.read()) != '/n') && (c != -1)) {
sb.append((char) c);
}
// System.out.println("receive text="+sb.toString());
String text = sb.toString();
if(text==null||text.length()==0){
clear();
form.stringItem.setText("与对方失去连接!");
form.removeCommand(form.comOk);
form.delete(1);
}
else
form.stringItem.setText(sb.toString());
}
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
return true;
}
/**
* 断开连接
*/
public void clear() {
try {
if(dataOutputStream!=null){
dataOutputStream.close();
dataOutputStream=null;
}
if(dataInputStream!=null){
dataInputStream.close();
dataInputStream=null;
}
if(streamConnection!=null){
streamConnection.close();
streamConnection=null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}