name="android.permission.BLUETOOTH"/>
添加权限
2、蓝牙搜索
a)
IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_NAME_CHANGED);
mContext.registerReceiver(mReceiver,filter);
注册广播
b)
mBtAdapter.startDiscovery();
开始扫描外围设备
c)退出,停止搜索,注销广播
mBtAdapter.cancelDiscovery();
privatevoidunregisterReceiver(){
if(mReceiverRegisted&&mContext!
=null){
mContext.unregisterReceiver(mReceiver);
mReceiverRegisted=false;
}
}
3、蓝牙连接
a)
mConnectThread=newConnectThread(device,secure);
mConnectThread.start();
新建连接线程并启动
privateclassConnectThreadextendsThread{
privatefinalBluetoothSocketmmSocket;
privatefinalBluetoothDevicemmDevice;
privateStringmSocketType;
publicConnectThread(BluetoothDevicedevice,booleansecure){
mmDevice=device;
BluetoothSockettmp=null;
mSocketType=secure?
"Secure":
"Insecure";
try{
if(secure){
tmp=device.createRfcommSocketToServiceRecord(SPP_UUID);
}else{
tmp=device
.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
}
}catch(IOExceptione){
}
mmSocket=tmp;
}
publicvoidrun(){
setName("ConnectThread"+mSocketType);
if(mmSocket!
=null){
try{
mmSocket.connect();
}catch(IOExceptione){
try{
mmSocket.close();
}catch(IOExceptione2){}
connectionFailed(mmDevice);
return;
}
synchronized(BluetoothConnectClient.this){
mConnectThread=null;
}
mCount=0;
connected(mmSocket,mmDevice,mSocketType);
}
}
b)创建BluetoothSocket,并建立Socket连接
publicvoidcancel(){
try{
if(null!
=mmSocket){
mmSocket.close();
}
}catch(IOExceptione){
Logger.e(TAG+"connectcancle:
",e);
}
}
}
publicsynchronizedvoidconnected(BluetoothSocketsocket,
BluetoothDevicedevice,finalStringsocketType){
ReadWriterBufferbuffer=newReadWriterBuffer();
mWriteThread=newWriteThread(device,socket,socketType,buffer);
mWriteThread.start();
OutputStreamtmpOut=null;
try{
tmpOut=socket.getOutputStream();
}catch(IOExceptione){
Logger.e(TAG+"connect",e);
}
mRunnable=newThread(newWriteRunnable(device,buffer,tmpOut));
mRunnable.start();
mReadThread=newReadThread(device,socket,socketType);
mReadThread.start();
}
c)创建读线程,创建写线程
d)写线程WriteRunnable,写入本地缓冲区域ReadWriterBuffer;写WriteThread,写入输出流。
classWriteRunnableimplementsRunnable{
privatefinalBluetoothDevicemmDevice;
privateReadWriterBuffermBuffer;
privateOutputStreammOut;
privateWriteRunnable(BluetoothDevicedevice,ReadWriterBufferbuffer,
OutputStreamout){
this.mmDevice=device;
this.mBuffer=buffer;
this.mOut=out;
}
@Override
publicvoidrun(){
while(mFlag){
mBuffer.write(mOut);
try{
Thread.sleep(Constants.INTERVEL_TIME);
}catch(InterruptedExceptione){
Logger.e(TAG+"mFlag:
"+mFlag,e);
}
}
}
}
privateclassWriteThreadextendsHandlerThread{
privateHandlermmWriteHandler;
privateReadWriterBuffermBuffer;
publicWriteThread(BluetoothDevicedevice,BluetoothSocketsocket,
StringsocketType,ReadWriterBufferbuffer){
super("WriteThread");
this.mBuffer=buffer;
}
publicvoidstart(){
super.start();
mmWriteHandler=newHandler(this.getLooper()){
@Override
publicvoidhandleMessage(Messagemsg){
if(msg.what==MESSAGE_DATA_WRITHE){
byte[]data=(byte[])msg.obj;
intlen=data.length;
mBuffer.read(data,len);
}
}
};
}
publicvoidwrite(byte[]data){
if(mmWriteHandler!
=null){
Message.obtain(mmWriteHandler,MESSAGE_DATA_WRITHE,data)
.sendToTarget();
}
}
publicvoidcancel(){
this.quit();
}
}
e)
publicclassReadWriterBuffer{
privateStringTAG="ReadWriterBuffer";
privateintmPos;
privatebyte[]mBuffer=newbyte[1024];
privateReadWriteLocklock;
publicReadWriterBuffer(){
lock=newReentrantReadWriteLock();
}
publicvoidread(byte[]res,intlen){
lock.readLock().lock();
System.arraycopy(res,0,mBuffer,mPos,len);
mPos=mPos+len;
lock.readLock().unlock();
}
publicvoidwrite(OutputStreamoutStream){
lock.writeLock().lock();
if(mPos!
=0){
try{
outStream.write(mBuffer,0,mPos);
outStream.flush();
}catch(IOExceptione){
Logger.d(TAG+"write");
}
}
mPos=0;
lock.writeLock().unlock();
}
}
自定义缓冲Buffer
f)创建读线程
privateclassReadThreadextendsThread{
privatefinalBluetoothDevicemmDevice;
privatefinalBluetoothSocketmmSocket;
privatefinalInputStreammmInStream;
publicReadThread(BluetoothDevicedevice,BluetoothSocketsocket,
StringsocketType){
mmDevice=device;
mmSocket=socket;
InputStreamtmpIn=null;
try{
tmpIn=socket.getInputStream();
}catch(IOExceptione){
}
mmInStream=tmpIn;
}
publicvoidrun(){
byte[]buffer=newbyte[1024];
intbytes;
while(true){
try{
bytes=mmInStream.read(buffer);
dataReceived(buffer,bytes);
}catch(IOExceptione){
connectionLost(mmDevice);
break;
}
}
}
publicvoidcancel(){
try{
if(null!
=mmSocket){
mmSocket.close();
}
}catch(IOExceptione){
}
}
}
g)使用Handler把数据抛给主线程
privatevoidsendDataReceivedMessage(byte[]data){
if(mMainHandler!
=null){
Messagemsg=mMainHandler.obtainMessage(MESSAGE_DATA_RECEIVED);
msg.obj=data;
mMainHandler.sendMessage(msg);
}
}
privateHandlermMainHandler=newHandler(Looper.getMainLooper()){
@Override
publicvoidhandleMessage(Messagemsg){
if(mConnectClientListener==null){
return;
}
switch(msg.what){
caseMESSAGE_DATA_RECEIVED:
{
byte[]data=(byte[])msg.obj;
mDataDecoder.parseKeyEvent(data,data.length);
break;
}
default:
break;
}
}
};
h)解析数据
voidparseKeyEvent(byte[]data,intlen){
StringBuffersb=newStringBuffer();
for(inti=0;isb.append(data[i]+"|");
}
if((len<3)||(mDataParsedListener==null)){
return;
}
if(len==3){
parseData(data,len);
return;
intl=len%3;
System.arraycopy(data,0,buffer,pos,len-l);
intsize=len-l+pos;
intoffset=0;
if(size>=1024){
Logger.d(TAG+"size"+size);
}
while(offsetbyte[]tmp=newbyte[3];
intlength=tmp.length;
if(offset+length>size){
pos=0;
return;
}
System.arraycopy(buffer,offset,tmp,0,tmp.length);
parseData(tmp,length);
offset=offset+length;
}
pos=size-offset;
}
补充知识点:
蓝牙配对,连接蓝牙规范profile,蓝牙服务(音响,耳机,文件传输),BLE蓝牙,蓝牙硬件支持(Android设备,iOS设备),蓝牙独享,无符号十六进制转换