BluetoothCharService.docx
《BluetoothCharService.docx》由会员分享,可在线阅读,更多相关《BluetoothCharService.docx(16页珍藏版)》请在冰豆网上搜索。
BluetoothCharService
*BluetoothCharService.java
Copyright(C)2009TheAndroidOpenSourceProject
*
*LicensedundertheApacheLicense,Version2.0(the"License");
*youmaynotusethisfileexceptincompliancewiththeLicense.
*YoumayobtainacopyoftheLicenseat
*
*http:
//www.apache.org/licenses/LICENSE-2.0
*
*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
*SeetheLicenseforthespecificlanguagegoverningpermissionsand
*limitationsundertheLicense.
*/
packagecom.example.android.BluetoothChat;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.UUID;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothDevice;
importandroid.bluetooth.BluetoothServerSocket;
importandroid.bluetooth.BluetoothSocket;
importandroid.content.Context;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.util.Log;
/**
*ThisclassdoesalltheworkforsettingupandmanagingBluetooth
*connectionswithotherdevices.Ithasathreadthatlistensfor
*incomingconnections,athreadforconnectingwithadevice,anda
*threadforperformingdatatransmissionswhenconnected.
*/
publicclassBluetoothChatService{
//Debugging
privatestaticfinalStringTAG="BluetoothChatService";
privatestaticfinalbooleanD=true;
//NamefortheSDPrecordwhencreatingserversocket
privatestaticfinalStringNAME="BluetoothChat";
//UniqueUUIDforthisapplication
privatestaticfinalUUIDMY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//Memberfields
privatefinalBluetoothAdaptermAdapter;
privatefinalHandlermHandler;
privateAcceptThreadmAcceptThread;
privateConnectThreadmConnectThread;
privateConnectedThreadmConnectedThread;
privateintmState;
//Constantsthatindicatethecurrentconnectionstate
publicstaticfinalintSTATE_NONE=0;//we'redoingnothing
publicstaticfinalintSTATE_LISTEN=1;//nowlisteningforincomingconnections
publicstaticfinalintSTATE_CONNECTING=2;//nowinitiatinganoutgoingconnection
publicstaticfinalintSTATE_CONNECTED=3;//nowconnectedtoaremotedevice
/**
*Constructor.PreparesanewBluetoothChatsession.
*@paramcontextTheUIActivityContext
*@paramhandlerAHandlertosendmessagesbacktotheUIActivity
*/
publicBluetoothChatService(Contextcontext,Handlerhandler){
mAdapter=BluetoothAdapter.getDefaultAdapter();
mState=STATE_NONE;
mHandler=handler;
}
/**
*Setthecurrentstateofthechatconnection
*@paramstateAnintegerdefiningthecurrentconnectionstate
*/
privatesynchronizedvoidsetState(intstate){
if(D)Log.d(TAG,"setState()"+mState+"->"+state);
mState=state;
//GivethenewstatetotheHandlersotheUIActivitycanupdate
mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE,state,-1).sendToTarget();
}
/**
*Returnthecurrentconnectionstate.*/
publicsynchronizedintgetState(){
returnmState;
}
/**
*Startthechatservice.SpecificallystartAcceptThreadtobegina
*sessioninlistening(server)mode.CalledbytheActivityonResume()*/
publicsynchronizedvoidstart(){
if(D)Log.d(TAG,"start");
//Cancelanythreadattemptingtomakeaconnection
if(mConnectThread!
=null){mConnectThread.cancel();mConnectThread=null;}
//Cancelanythreadcurrentlyrunningaconnection
if(mConnectedThread!
=null){mConnectedThread.cancel();mConnectedThread=null;}
//StartthethreadtolistenonaBluetoothServerSocket
if(mAcceptThread==null){
mAcceptThread=newAcceptThread();
mAcceptThread.start();
}
setState(STATE_LISTEN);
}
/**
*StarttheConnectThreadtoinitiateaconnectiontoaremotedevice.
*@paramdeviceTheBluetoothDevicetoconnect
*/
publicsynchronizedvoidconnect(BluetoothDevicedevice){
if(D)Log.d(TAG,"connectto:
"+device);
//Cancelanythreadattemptingtomakeaconnection
if(mState==STATE_CONNECTING){
if(mConnectThread!
=null){mConnectThread.cancel();mConnectThread=null;}
}
//Cancelanythreadcurrentlyrunningaconnection
if(mConnectedThread!
=null){mConnectedThread.cancel();mConnectedThread=null;}
//Startthethreadtoconnectwiththegivendevice
mConnectThread=newConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
}
/**
*StarttheConnectedThreadtobeginmanagingaBluetoothconnection
*@paramsocketTheBluetoothSocketonwhichtheconnectionwasmade
*@paramdeviceTheBluetoothDevicethathasbeenconnected
*/
publicsynchronizedvoidconnected(BluetoothSocketsocket,BluetoothDevicedevice){
if(D)Log.d(TAG,"connected");
//Cancelthethreadthatcompletedtheconnection
if(mConnectThread!
=null){mConnectThread.cancel();mConnectThread=null;}
//Cancelanythreadcurrentlyrunningaconnection
if(mConnectedThread!
=null){mConnectedThread.cancel();mConnectedThread=null;}
//Canceltheacceptthreadbecauseweonlywanttoconnecttoonedevice
if(mAcceptThread!
=null){mAcceptThread.cancel();mAcceptThread=null;}
//Startthethreadtomanagetheconnectionandperformtransmissions
mConnectedThread=newConnectedThread(socket);
mConnectedThread.start();
//SendthenameoftheconnecteddevicebacktotheUIActivity
Messagemsg=mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
Bundlebundle=newBundle();
bundle.putString(BluetoothChat.DEVICE_NAME,device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
*Stopallthreads
*/
publicsynchronizedvoidstop(){
if(D)Log.d(TAG,"stop");
if(mConnectThread!
=null){mConnectThread.cancel();mConnectThread=null;}
if(mConnectedThread!
=null){mConnectedThread.cancel();mConnectedThread=null;}
if(mAcceptThread!
=null){mAcceptThread.cancel();mAcceptThread=null;}
setState(STATE_NONE);
}
/**
*WritetotheConnectedThreadinanunsynchronizedmanner
*@paramoutThebytestowrite
*@seeConnectedThread#write(byte[])
*/
publicvoidwrite(byte[]out){
//Createtemporaryobject
ConnectedThreadr;
//SynchronizeacopyoftheConnectedThread
synchronized(this){
if(mState!
=STATE_CONNECTED)return;
r=mConnectedThread;
}
//Performthewriteunsynchronized
r.write(out);
}
/**
*IndicatethattheconnectionattemptfailedandnotifytheUIActivity.
*/
privatevoidconnectionFailed(){
setState(STATE_LISTEN);
//SendafailuremessagebacktotheActivity
Messagemsg=mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundlebundle=newBundle();
bundle.putString(BluetoothChat.TOAST,"Unabletoconnectdevice");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
*IndicatethattheconnectionwaslostandnotifytheUIActivity.
*/
privatevoidconnectionLost(){
setState(STATE_LISTEN);
//SendafailuremessagebacktotheActivity
Messagemsg=mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundlebundle=newBundle();
bundle.putString(BluetoothChat.TOAST,"Deviceconnectionwaslost");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
*Thisthreadrunswhilelisteningforincomingconnections.Itbehaves
*likeaserver-sideclient.Itrunsuntilaconnectionisaccepted
*(oruntilcancelled).
*/
privateclassAcceptThreadextendsThread{
//Thelocalserversocket
privatefinalBluetoothServerSocketmmServerSocket;
publicAcceptThread(){
BluetoothServerSockettmp=null;
//Createanewlisteningserversocket
try{
tmp=mAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);
}catch(IOExceptione){
Log.e(TAG,"listen()failed",e);
}
mmServerSocket=tmp;
}
publicvoidrun(){
if(D)Log.d(TAG,"BEGINmAcceptThread"+this);
setName("AcceptThread");
BluetoothSocketsocket=null;
//Listentotheserversocketifwe'renotconnected
while(mState!
=STATE_CONNECTED){
try{
//Thisisablockingcallandwillonlyreturnona
//successfulconnectionoranexception
socket=mmServerSocket.accept();
}catch(IOExceptione){
Log.e(TAG,"accept()failed",e);
break;
}
//Ifaconnectionwasaccepted
if(socket!
=null){
synchronized(BluetoothChatService.this){
switch(mState){
caseSTATE_LISTEN:
caseSTATE_CONNECTING:
//Situationnormal.Starttheconnectedthread.
connected(socket,socket.getRemoteDevice());
break;
caseSTATE_NONE:
caseSTATE_CONNECTED:
//Eithernotreadyoralreadyconnected.Terminatenewsocket.
try{
socket.close();
}catch(IOExceptione){
Log.e(TAG,"Couldnotcloseunwantedsocket",e);
}
break;
}
}
}
}
if(D)Log.i(TAG,"ENDmAcceptThread");
}
publicvoidcancel(){
if(D)Log.d(TAG,"cancel"+this);
try{
mmServerSocket.close();
}catch(IOExceptione){
Log.e(TAG,"close()ofserverfailed",e);
}
}
}
/**
*Thisthreadrunswhileattemptingtomakeanoutgoingconnection
*withadevice.Itrunsstraightthrough;theconnectioneither
*succeedsorfails.
*/
privateclassConnectThreadextendsThread{
privatefinalBluetoothSocketmmSocket;
privatefinalBluetoothDevicemmDevice;
publicConnectThread(BluetoothDevicedevice){
mmDevice=device;
BluetoothSockettmp=null;
//GetaBluetoothSocketforaconnectionwiththe
//givenBluetoothDevice
try{
tmp=device.createRfcommSocketToServiceRecord(MY_UUID);
}catch(IOExceptione){
Log.e(TAG,"create()failed",