?? 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:
//查詢完成后,啟動客戶端
if(sr != null){
devices.setTitle("sending picture...");
handle = new ClientHandle();
return;
}
message = "service search completed";
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 + -