📄 btclient.java
字号:
package com.j2medev.chapter9;
import java.io.*;
import java.util.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.*;
public class BTClient implements DiscoveryListener,CommandListener {
private BTMIDlet midlet = null;
//本地设备
private LocalDevice bt = null;
//显示查找到的设备列表
private List devices = null;
//存储查找到的设备,以便后面查找设备上的服务
private Vector deviceVector = new Vector();
//存储我们感兴趣的服务
private ServiceRecord sr = null;
private ClientHandle handle = null;
public BTClient(BTMIDlet _midlet) {
midlet = _midlet;
devices = new List("inquring devices...",List.IMPLICIT);
//开始查找设备
initBluetooth();
handle = new ClientHandle();
Display.getDisplay(midlet).setCurrent(devices);
}
private void initBluetooth(){
try {
bt = LocalDevice.getLocalDevice();
bt.setDiscoverable(DiscoveryAgent.GIAC);
//查找设备
bt.getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC,this);
} catch (BluetoothStateException ex) {
ex.printStackTrace();
showException(ex);
}
}
//显示异常信息
private void showException(Exception ex){
Alert a = BTMIDlet.getAlert(ex.toString(),AlertType.ERROR,2000);
Display.getDisplay(midlet).setCurrent(a);
}
public void deviceDiscovered(final RemoteDevice remoteDevice, DeviceClass deviceClass) {
//getFriendlyName()在某些机型中耗费时间,在单独线程中调用
new Thread(){
public void run(){
try {
devices.append(remoteDevice.getFriendlyName(false),null);
//将设备存储在deviceVector中
deviceVector.addElement(remoteDevice);
} catch (IOException ex) {
ex.printStackTrace();
showException(ex);
}
}
}.start();
}
public void servicesDiscovered(int i, ServiceRecord[] serviceRecord) {
//只存储第一个发现的服务
if(serviceRecord.length != 0){
sr = serviceRecord[0];
}
}
public void serviceSearchCompleted(int i, int i0) {
String message = "";
switch(i0){
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
//查询完成后,启动客户端
devices.setTitle("sending picture...");
handle = new ClientHandle();
return;
//break;
case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
message = "user cancel the search";
break;
case DiscoveryListener.SERVICE_SEARCH_ERROR:
message = "error when search service";
break;
case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
message = "the device is not reachale";
break;
case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
message = "don't find any record";
break;
default:
break;
}
devices.setTitle("no service");
Alert a = BTMIDlet.getAlert(message,AlertType.INFO,2000);
Display.getDisplay(midlet).setCurrent(a);
}
//设备查询完毕将被调用
public void inquiryCompleted(int i) {
switch(i){
case INQUIRY_COMPLETED:
devices.setTitle("devices");
break;
case INQUIRY_ERROR:
Alert alert = BTMIDlet.getAlert("query devices error",AlertType.ERROR,2000);
Display.getDisplay(midlet).setCurrent(alert,devices);
break;
case INQUIRY_TERMINATED:{
break;
}
default:
break;
}
//查找完成后再为设备列表添加CommandListener
devices.addCommand(new Command("back",Command.BACK,1));
devices.setCommandListener(this);
}
public void commandAction(Command command, Displayable displayable) {
if(command.getCommandType() == Command.BACK){
//返回
}
if(command == List.SELECT_COMMAND){
int i = devices.getSelectedIndex();
UUID[] uuids = new UUID[1];
uuids[0] = new UUID(0x0001);
try {
//查询指定设备上的服务
devices.setTitle("looking for services...");
bt.getDiscoveryAgent().searchServices(null,uuids,(RemoteDevice)deviceVector.elementAt(i),this);
} catch (BluetoothStateException ex) {
ex.printStackTrace();
showException(ex);
}
}
}
private class ClientHandle implements Runnable{
private Thread t = null;
ClientHandle(){
t = new Thread(this);
t.start();
}
public void run(){
//连接服务器
String url = sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
int i = url.indexOf(":");
String protocol = url.substring(0,i);
//根据不同的协议,采用不同的发送数据方式
if(protocol.equals("btspp")){
StreamConnection conn = null;
try {
//流连接情况下发送相对简单
conn = (StreamConnection)Connector.open(url);
OutputStream os = conn.openOutputStream();
os.write(midlet.getImage());
os.flush();
os.close();
conn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}else if(protocol.equals("btl2cap")){
L2CAPConnection conn = null;
try{
conn = (L2CAPConnection)Connector.open(url);
//L2CAPConnection是面向连接的,需要考虑MTU
int max = conn.getTransmitMTU();
byte[] img = midlet.getImage();
byte[] buffer = new byte[max];
int index = 0;
//每次发送一个缓冲区的数据,且不超过MTU
while(index <img.length){
//不足max的长度,需要截取一部分发送
if(img.length - index<max){
buffer = new byte[img.length-index];
System.arraycopy(img,index,buffer,0,img.length-index);
}else{
System.arraycopy(img,index,buffer,0,max);
}
conn.send(buffer);
index+=max;
}
conn.close();
} catch (Exception ex) {
showException(ex);
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -