用j2me 实现SPP协议,实现连接,配对,发送数据,蓝牙模块通过串口,连接的单片机。
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class BtSppMid extends MIDlet implements Runnable, CommandListener, ItemCommandListener {
public StreamConnection client = null;
//Bluetooth SPP 数据流
public DataInputStream dis = null;
public DataOutputStream dos = null;
public boolean running; //线程运行标志
public Display display = null;
public Form form = new Form("JB00 Bluetooth suite");
private Command cmdExit = new Command("Exit", Command.EXIT, 1);
private Command cmdConnect1 = new Command("Connect1", Command.SCREEN, 1); //连接查找到的SPP服务
private Command cmdSearch = new Command("Search device", Command.SCREEN, 1); //查找蓝牙设备
private Command cmdSrchService = new Command("Search service", Command.SCREEN, 1); //查找蓝牙服务
private Command cmdStopSrch = new Command("Stop", Command.SCREEN, 1); //停止蓝牙设备搜索
private Command cmdOK = new Command("OK", Command.OK, 1); //查找到设备后直接连接其SPP服务
public Command cmdConnect = new Command("Connect", Command.ITEM, 1);
DiscoveryAgent discoveryAgent;
DiscoveryListener discoveryListener;
//用于保存搜索到的设备
Vector devices = new Vector();
Vector devName = new Vector();
Vector devAdr = new Vector();
Vector devItem = new Vector();
//用于保存搜索到的服务
Vector services = new Vector();
//服务器服务记录
ServiceRecord record=null;
//搜索所得的设备地址
String deviceAddr;
String conURL;
public BtSppMid() {
super();
form.addCommand(cmdExit);
form.addCommand(cmdSearch);
form.setCommandListener(this);
discoveryListener = new MyDiscoveryListener(this);
}
protected void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
display.setCurrent(form);
running = true;
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
form.append("Bluetooth ready, please search device first./n");
} catch (BluetoothStateException e) {
form.append("Failed to use bluetooth!/nYou'd better checkout your bluetooth status./n");
pauseApp();
}
}
protected void pauseApp() {
// close();
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
running = false;
close();
}
public void commandAction(Command cmd, Displayable d) {
if (cmd == cmdExit) {
notifyDestroyed();
}
else if (cmd == cmdSearch)
{
try
{
//开始进行蓝牙设备查找
discoveryAgent.startInquiry(DiscoveryAgent.GIAC,discoveryListener);
form.append("Searching BT device../n");
}
catch (Exception e)
{
form.append("Searching error!/n");
return;
}
form.removeCommand(cmdSearch);
form.addCommand(cmdStopSrch);
form.addCommand(cmdSrchService); //添加发现服务命令
}
else if (cmd == cmdSrchService)
{
UUID uuid[] = {new UUID(0x1101)}; //0x1101是蓝牙SPP服务所对应的UUID
for (int i=0;i
{
RemoteDevice btDevice = (RemoteDevice)devices.elementAt(i);
try
{
discoveryAgent.searchServices(null, uuid, btDevice, discoveryListener); //在发现的设备上查找SPP服务
form.append("searching service../n");
} catch (IOException e) {
form.append("Search error!/n");
return;
}
break;
}
form.removeCommand(cmdSrchService);
form.addCommand(cmdConnect1);
}
else if (cmd == cmdConnect1)
{
conURL = ((ServiceRecord)services.elementAt(0)).getConnectionURL(0,false); //连接第一个被查找到的设备
form.append("Trying to connect1 "+conURL+"/n");
//开始蓝牙连接线程
new Thread(this).start();
}
else if (cmd == cmdStopSrch)
{
discoveryAgent.cancelInquiry(discoveryListener); //停止蓝牙设备查找/
}
}
public void run() {
client = null;
try {
client = (StreamConnection)Connector.open(conURL); //连接指定设备的SPP服务
form.append("Connected./n");
dis = client.openDataInputStream();
dos = client.openDataOutputStream();
form.removeCommand(cmdConnect);
form.removeCommand(cmdConnect1);
form.removeCommand(cmdSrchService);
form.removeCommand(cmdStopSrch);
for(int i=0; i
{
//连接成功后,移除所有设备所对应StringItem的连接命令
StringItem si = (StringItem)devItem.elementAt(i);
si.removeCommand(cmdConnect);
}
} catch (Exception e) {
form.append("Connect error!/n");
close();
return;
}
}
public void commandAction(Command c, Item item) {
String deviceName;
if(c == cmdConnect) //连接该设备的SPP服务
{
deviceName = ((StringItem)item).getText();
for (int i=0;i
{
if((String)devName.elementAt(i) == deviceName)
{
deviceAddr = (String) devAdr.elementAt(i); //从保存的设备地址中获取蓝牙地址
conURL = "btspp://"+deviceAddr+":1";
form.append("Connecting "+deviceName+"../n");
//开始蓝牙连接线程
new Thread(this).start();
break;
}
}
}
}
public void close() {
try {
if (dis != null) {
dis.close();
dis = null;
}
if (dos != null) {
dos.close();
dos = null;
}
if (client != null) {
client.close();
client = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendDataToBluetooth(String data)
{
try
{
dos.write(data.getBytes());
dos.flush();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
//蓝牙设备发现、服务发现处理
class MyDiscoveryListener implements DiscoveryListener {
BtSppMid midlet;
public MyDiscoveryListener(BtSppMid midlet) {
this.midlet = midlet;
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
String name = null;
StringItem tmpItem;
try {
name = btDevice.getFriendlyName(false); //查找设备名称
} catch (IOException e) {
}
//发现设备后,将其作为StringItem在屏幕上显示,以添加命令,并存入vector
tmpItem = new StringItem(null, name);
midlet.devItem.addElement(tmpItem);
midlet.form.append((StringItem)midlet.devItem.lastElement());
midlet.devices.addElement(btDevice);
}
public void inquiryCompleted(int discType) {
for(int i=0; i
{
StringItem si = (StringItem)midlet.devItem.elementAt(i);
RemoteDevice rd = (RemoteDevice)midlet.devices.elementAt(i);
String name = null;
String adr = null;
try {
name = rd.getFriendlyName(false);
adr = rd.getBluetoothAddress();
midlet.devName.addElement(name);
midlet.devAdr.addElement(adr);
} catch (IOException e) {
}
si.setText(name); //设置StringItem为设备名称
}
midlet.form.append("/nSearching complete./n");
for(int i=0; i
{
StringItem si = (StringItem)midlet.devItem.elementAt(i);
si.setDefaultCommand(midlet.cmdConnect); //为每个设备添加连接命令
si.setItemCommandListener(midlet);
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
if(servRecord.length > -1)
{
for(int i = 0; i < servRecord.length; i++)
{
midlet.services.addElement(servRecord[i]);
midlet.form.append(servRecord[i].toString()+"/n");
}
}
else{
midlet.form.append("No service found!/n");
}
}
public void serviceSearchCompleted(int transID, int responseCode) {
midlet.form.append(responseCode+" is the srching result./n");
}
}