Android蓝牙通信聊天实现发送和接受功能
很不错的蓝牙通信demo实现发送和接受功能,就用了两个类就实现了,具体内容如下
说下思路把主要有两个类主界面类和蓝牙聊天服务类 。首先创建线程实际上就是创建BluetoothChatService()(蓝牙聊天服务类)这个时候把handler传过去这样就可以操作UI界面了,在线程中不断轮询读取蓝牙消息,当主界面点击发送按钮时调用BluetoothChatService的发送方法write方法,这里的write方法使用了handler发送消息,在主界面显示,另一个客户端不断读取蓝牙消息类似的有个read方法同样显示到界面上去,这样就完成了通信了。
importjava.util.ArrayList;
importjava.util.Set;
importandroid.app.Activity;
importandroid.app.AlertDialog;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothDevice;
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.DialogInterface;
importandroid.content.Intent;
importandroid.content.IntentFilter;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.util.Log;
importandroid.view.Menu;
importandroid.view.MenuItem;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.view.Window;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.TextView;
importandroid.widget.Toast;
publicclassBluetoothChatextendsActivity{
//MessagetypessentfromtheBluetoothChatServiceHandler
publicstaticfinalintMESSAGE_STATE_CHANGE=1;
publicstaticfinalintMESSAGE_READ=2;
publicstaticfinalintMESSAGE_WRITE=3;
publicstaticfinalintMESSAGE_DEVICE_NAME=4;
publicstaticfinalintMESSAGE_TOAST=5;
//KeynamesreceivedfromtheBluetoothChatServiceHandler
publicstaticfinalStringDEVICE_NAME="device_name";
publicstaticfinalStringTOAST="toast";
//Intentrequestcodes
privatestaticfinalintREQUEST_CONNECT_DEVICE=1;
privatestaticfinalintREQUEST_ENABLE_BT=2;
privateTextViewmTitle;
privateEditTexttext_chat;
privateEditTexttext_input;
privateButtonbut_On_Off;
privateButtonbut_search;//------>在菜单中可以搜索
privateButtonbut_create;//------>在菜单中设置"可被发现"
privateButtonmSendButton;
//连接到的蓝牙设备的名称
privateStringmConnectedDeviceName;
//Stringbufferforoutgoingmessages
privateStringBuffermOutStringBuffer;
//LocalBluetoothadapter
privateBluetoothAdaptermBluetoothAdapter=null;
//Memberobjectforthechatservices
privateBluetoothChatServicemChatService=null;
privateArrayList<String>mPairedDevicesList=newArrayList<String>();
privateArrayList<String>mNewDevicesList=newArrayList<String>();
privateString[]strName;
privateStringaddress;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
mTitle=(TextView)this.findViewById(R.id.text_title);
text_chat=(EditText)this.findViewById(R.id.text_chat);
text_input=(EditText)this.findViewById(R.id.text_input);
but_On_Off=(Button)this.findViewById(R.id.but_off_on);
but_search=(Button)this.findViewById(R.id.but_search_div);
but_create=(Button)this.findViewById(R.id.but_cjlj);
mSendButton=(Button)this.findViewById(R.id.but_fsxx);
//获得本地的蓝牙适配器
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//如果为null,说明没有蓝牙设备
if(mBluetoothAdapter==null){
Toast.makeText(this,"没有蓝牙设备",Toast.LENGTH_LONG).show();
finish();
return;
}
if(mBluetoothAdapter.isEnabled()){
but_On_Off.setText("关闭蓝牙");
}else{
but_On_Off.setText("开启蓝牙");
}
but_On_Off.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
if(!mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.enable();
Toast.makeText(BluetoothChat.this,"蓝牙已开启",
Toast.LENGTH_SHORT).show();
but_On_Off.setText("关闭蓝牙");
}else{
mBluetoothAdapter.disable();
Toast.makeText(BluetoothChat.this,"蓝牙已关闭",
Toast.LENGTH_SHORT).show();
but_On_Off.setText("开启蓝牙");
}
}
});
but_search.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
searchDevice();
}
});
but_create.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
finalEditTextet=newEditText(BluetoothChat.this);
et.setSingleLine();
et.setText(mBluetoothAdapter.getName());
newAlertDialog.Builder(BluetoothChat.this)
.setTitle("请输入房间名:")
.setView(et)
.setPositiveButton("确定",
newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,
intwhich){
Stringname=et.getText().toString()
.trim();
if(name.equals("")){
Toast.makeText(BluetoothChat.this,
"请输入房间名",
Toast.LENGTH_SHORT).show();
return;
}
//设置房间名
mBluetoothAdapter.setName(name);
}
})
.setNegativeButton("取消",
newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,
intwhich){
}
}).create().show();
//创建连接,也就是设备本地蓝牙设备可被其他用户的蓝牙搜到
ensureDiscoverable();
}
});
//获得一个已经配对的蓝牙设备的set集合
Set<BluetoothDevice>pairedDevices=mBluetoothAdapter
.getBondedDevices();
if(pairedDevices.size()>0){
for(BluetoothDevicedevice:pairedDevices){
mPairedDevicesList.add("已配对:"+device.getName()+"\n"
+device.getAddress());
}
}else{
Toast.makeText(this,"没有已配对的设备",Toast.LENGTH_SHORT).show();
}
//当发现一个新的蓝牙设备时注册广播
IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver,filter);
//当搜索完毕后注册广播
filter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver,filter);
}
@Override
publicvoidonStart(){
super.onStart();
//IfBTisnoton,requestthatitbeenabled.
//setupChat()willthenbecalledduringonActivityResult
if(!mBluetoothAdapter.isEnabled()){
IntentenableIntent=newIntent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
//Otherwise,setupthechatsession
}else{
if(mChatService==null)
setupChat();
}
}
@Override
publicsynchronizedvoidonResume(){
super.onResume();
//PerformingthischeckinonResume()coversthecaseinwhichBTwas
//notenabledduringonStart(),sowewerepausedtoenableit...
//onResume()willbecalledwhenACTION_REQUEST_ENABLEactivity
//returns.
if(mChatService!=null){
//OnlyifthestateisSTATE_NONE,doweknowthatwehaven't
//startedalready
if(mChatService.getState()==BluetoothChatService.STATE_NONE){
//StarttheBluetoothchatservices
mChatService.start();
}
}
}
privatevoidsetupChat(){
mSendButton.setOnClickListener(newOnClickListener(){
publicvoidonClick(Viewv){
//Sendamessageusingcontentoftheedittextwidget
Stringmessage=text_input.getText().toString();
sendMessage(message);
}
});
//InitializetheBluetoothChatServicetoperformbluetoothconnections
mChatService=newBluetoothChatService(this,mHandler);
//Initializethebufferforoutgoingmessages
mOutStringBuffer=newStringBuffer("");
}
@Override
publicvoidonDestroy(){
super.onDestroy();
//StoptheBluetoothchatservices
if(mChatService!=null)
mChatService.stop();
//Makesurewe'renotdoingdiscoveryanymore
if(mBluetoothAdapter!=null){
mBluetoothAdapter.cancelDiscovery();
}
//Unregisterbroadcastlisteners
this.unregisterReceiver(mReceiver);
}
/**使本地的蓝牙设备可被发现*/
privatevoidensureDiscoverable(){
if(mBluetoothAdapter.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
IntentdiscoverableIntent=newIntent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(discoverableIntent);
}
}
/**
*Sendsamessage.
*
*@parammessage
*Astringoftexttosend.
*/
privatevoidsendMessage(Stringmessage){
//Checkthatwe'reactuallyconnectedbeforetryinganything
if(mChatService.getState()!=BluetoothChatService.STATE_CONNECTED){
Toast.makeText(this,"没有连接上",Toast.LENGTH_SHORT).show();
return;
}
//Checkthatthere'sactuallysomethingtosend
if(message.length()>0){
//GetthemessagebytesandtelltheBluetoothChatServicetowrite
byte[]send=message.getBytes();
mChatService.write(send);
//Resetoutstringbuffertozeroandcleartheedittextfield
mOutStringBuffer.setLength(0);
text_input.setText(mOutStringBuffer);
}
}
//TheHandlerthatgetsinformationbackfromtheBluetoothChatService
privatefinalHandlermHandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
caseMESSAGE_STATE_CHANGE:
switch(msg.arg1){
caseBluetoothChatService.STATE_CONNECTED:
mTitle.setText("已经连接");
mTitle.append(mConnectedDeviceName);
//mConversationArrayAdapter.clear();
break;
caseBluetoothChatService.STATE_CONNECTING:
mTitle.setText("正在连接中...");
break;
caseBluetoothChatService.STATE_LISTEN:
caseBluetoothChatService.STATE_NONE:
mTitle.setText("未连接上");
break;
}
break;
caseMESSAGE_WRITE:
byte[]writeBuf=(byte[])msg.obj;
//constructastringfromthebuffer
StringwriteMessage=newString(writeBuf);
//mConversationArrayAdapter.add("Me:"+writeMessage);
text_chat.append("我:"+writeMessage+"\n");
break;
caseMESSAGE_READ:
byte[]readBuf=(byte[])msg.obj;
//constructastringfromthevalidbytesinthebuffer
StringreadMessage=newString(readBuf,0,msg.arg1);
//mConversationArrayAdapter.add(mConnectedDeviceName+":"+
//readMessage);
text_chat.append(mConnectedDeviceName+":"+readMessage
+"\n");
break;
caseMESSAGE_DEVICE_NAME:
//savetheconnecteddevice'sname
mConnectedDeviceName=msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(),
"连接到"+mConnectedDeviceName,Toast.LENGTH_SHORT)
.show();
break;
caseMESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST),Toast.LENGTH_SHORT)
.show();
break;
}
}
};
//连接蓝牙设备
privatevoidlinkDevice(){
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
intcou=mPairedDevicesList.size()+mNewDevicesList.size();
if(cou==0){
Toast.makeText(BluetoothChat.this,"没有搜索到可用的蓝牙设备",
Toast.LENGTH_SHORT).show();
return;
}
//把已经配对的蓝牙设备和新发现的蓝牙设备的名称都放入数组中,以便在对话框列表中显示
strName=newString[cou];
for(inti=0;i<mPairedDevicesList.size();i++){
strName[i]=mPairedDevicesList.get(i);
}
for(inti=mPairedDevicesList.size();i<strName.length;i++){
strName[i]=mNewDevicesList.get(i-mPairedDevicesList.size());
}
address=strName[0].substring(strName[0].length()-17);
newAlertDialog.Builder(BluetoothChat.this)
.setTitle("搜索到的蓝牙设备:")
.setSingleChoiceItems(strName,0,
newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,
intwhich){
//当用户点击选中的蓝牙设备时,取出选中的蓝牙设备的MAC地址
address=strName[which].split("\\n")[1].trim();
}
})
.setPositiveButton("连接",newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
if(address==null){
Toast.makeText(BluetoothChat.this,"请先连接外部蓝牙设备",
Toast.LENGTH_SHORT).show();
return;
}
Log.i("sxd","address:"+address);
//GettheBLuetoothDeviceobject
BluetoothDevicedevice=mBluetoothAdapter
.getRemoteDevice(address);
//Attempttoconnecttothedevice
mChatService.connect(device);
}
})
.setNegativeButton("取消",newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
}
}).create().show();
}
//搜索蓝牙设备蓝牙设备
privatevoidsearchDevice(){
mTitle.setText("正在努力搜索中...");
setProgressBarIndeterminateVisibility(true);
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
mNewDevicesList.clear();
mBluetoothAdapter.startDiscovery();
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
menu.add(0,1,0,"搜索设备");
menu.add(0,2,0,"可被发现");
returntrue;
}
privatefinalBroadcastReceivermReceiver=newBroadcastReceiver(){
@Override
publicvoidonReceive(Contextcontext,Intentintent){
Stringaction=intent.getAction();
//当发现一个新的蓝牙设备时
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevicedevice=intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Ifit'salreadypaired,skipit,becauseit'sbeenlisted
//already
if(device.getBondState()!=BluetoothDevice.BOND_BONDED){
Strings="未配对:"+device.getName()+"\n"
+device.getAddress();
if(!mNewDevicesList.contains(s))
mNewDevicesList.add(s);
}
//Whendiscoveryisfinished,changetheActivitytitle
}elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)){
setProgressBarIndeterminateVisibility(false);
if(mNewDevicesList.size()==0){
Toast.makeText(BluetoothChat.this,"没有发现新设备",
Toast.LENGTH_SHORT).show();
}
mTitle.setText("未连接");
linkDevice();
}
}
};
@Override
publicbooleanonOptionsItemSelected(MenuItemitem){
switch(item.getItemId()){
case1:
searchDevice();
returntrue;
case2:
//Ensurethisdeviceisdiscoverablebyothers
ensureDiscoverable();
returntrue;
}
returnfalse;
}
}
packagecom.it2388.bluetooth;
/*
*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.
*/
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.Ithasathreadthatlistensforincoming
*connections,athreadforconnectingwithadevice,andathreadfor
*performingdatatransmissionswhenconnected.
*
**这个类做所有的工作,建立和管理蓝牙与其他设备的连接。它有一个线程监听传入的连接,一个用于连接一个设备的线程,和一个当连接时执行数据传输的线程。
*/
publicclassBluetoothChatService{
//Debugging
privatestaticfinalStringTAG="BluetoothChatService";
privatestaticfinalbooleanD=true;
//NamefortheSDPrecordwhencreatingserversocket对于SDP记录名称创建服务器套接字时
privatestaticfinalStringNAME="BluetoothChat";
//UniqueUUIDforthisapplication
privatestaticfinalUUIDMY_UUID=UUID
.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
//Memberfields
privatefinalBluetoothAdaptermAdapter;
privatefinalHandlermHandler;
privateAcceptThreadmAcceptThread;
privateConnectThreadmConnectThread;
privateConnectedThreadmConnectedThread;
privateintmState;
//Constantsthatindicatethecurrentconnectionstate
publicstaticfinalintSTATE_NONE=0;//we'redoingnothing我们什么都不做
publicstaticfinalintSTATE_LISTEN=1;//nowlisteningforincoming现在监听
//connections
publicstaticfinalintSTATE_CONNECTING=2;//nowinitiatinganoutgoing
//启动一个外向
//connection
publicstaticfinalintSTATE_CONNECTED=3;//nowconnectedtoaremote
//连接到一个远程
//device
/**
*Constructor.PreparesanewBluetoothChatsession.
*
*@paramcontext
*TheUIActivityContext
*@paramhandler
*AHandlertosendmessagesbacktotheUIActivity
*/
publicBluetoothChatService(Contextcontext,Handlerhandler){
mAdapter=BluetoothAdapter.getDefaultAdapter();
mState=STATE_NONE;
mHandler=handler;
}
/**
*Setthecurrentstateofthechatconnection
*
*@paramstate
*Anintegerdefiningthecurrentconnectionstate
*/
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.
*
*@paramdevice
*TheBluetoothDevicetoconnect
*/
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
*
*@paramsocket
*TheBluetoothSocketonwhichtheconnectionwasmade
*@paramdevice
*TheBluetoothDevicethathasbeenconnected
*/
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;
}
//Canceltheacceptthreadbecauseweonlywanttoconnecttoone
//device
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
*
*@paramout
*Thebytestowrite
*@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,"不能连接到设备");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
*IndicatethattheconnectionwaslostandnotifytheUIActivity.
*/
privatevoidconnectionLost(){
setState(STATE_LISTEN);
//SendafailuremessagebacktotheActivity
Messagemsg=mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundlebundle=newBundle();
bundle.putString(BluetoothChat.TOAST,"设备连接中断");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
*Thisthreadrunswhilelisteningforincomingconnections.Itbehaves
*likeaserver-sideclient.Itrunsuntilaconnectionisaccepted(or
*untilcancelled).
*/
privateclassAcceptThreadextendsThread{
//Thelocalserversocket
privatefinalBluetoothServerSocketmmServerSocket;
publicAcceptThread(){
BluetoothServerSockettmp=null;
//Createanewlisteningserversocket
try{
tmp=mAdapter
.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);
}catch(IOExceptione){
Log.e("sxd","========ufcommexception=======",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("sxd","--->acceptsocketfailed<---",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.Terminate
//newsocket.
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);
}
}
}
/**
*Thisthreadrunswhileattemptingtomakeanoutgoingconnectionwitha
*device.Itrunsstraightthrough;theconnectioneithersucceedsor
*fails.
*/
privateclassConnectThreadextendsThread{
privatefinalBluetoothSocketmmSocket;
privatefinalBluetoothDevicemmDevice;
publicConnectThread(BluetoothDevicedevice){
mmDevice=device;
BluetoothSockettmp=null;
//GetaBluetoothSocketforaconnectionwiththe
//givenBluetoothDevice
try{
tmp=device.createRfcommSocketToServiceRecord(MY_UUID);
}catch(IOExceptione){
Log.e(TAG,"create()failed",e);
}
mmSocket=tmp;
}
publicvoidrun(){
Log.i(TAG,"BEGINmConnectThread");
setName("ConnectThread");
//Alwayscanceldiscoverybecauseitwillslowdownaconnection
mAdapter.cancelDiscovery();
//MakeaconnectiontotheBluetoothSocket
try{
//Thisisablockingcallandwillonlyreturnona
//successfulconnectionoranexception
mmSocket.connect();
}catch(IOExceptione){
Log.e("sxd","链接发生了异常",e);
connectionFailed();
//Closethesocket
try{
mmSocket.close();
}catch(IOExceptione2){
Log.e(TAG,
"unabletoclose()socketduringconnectionfailure",
e2);
}
//Starttheserviceovertorestartlisteningmode
BluetoothChatService.this.start();
return;
}
//ResettheConnectThreadbecausewe'redone
synchronized(BluetoothChatService.this){
mConnectThread=null;
}
//Starttheconnectedthread
connected(mmSocket,mmDevice);
}
publicvoidcancel(){
try{
mmSocket.close();
}catch(IOExceptione){
Log.e(TAG,"close()ofconnectsocketfailed",e);
}
}
}
/**
*Thisthreadrunsduringaconnectionwitharemotedevice.Ithandlesall
*incomingandoutgoingtransmissions.
*
*和已经建立连接的设置进行数据的传输
*/
privateclassConnectedThreadextendsThread{
privatefinalBluetoothSocketmmSocket;
privatefinalInputStreammmInStream;
privatefinalOutputStreammmOutStream;
publicConnectedThread(BluetoothSocketsocket){
Log.d(TAG,"createConnectedThread");
mmSocket=socket;
InputStreamtmpIn=null;
OutputStreamtmpOut=null;
//GettheBluetoothSocketinputandoutputstreams
try{
tmpIn=socket.getInputStream();
tmpOut=socket.getOutputStream();
}catch(IOExceptione){
Log.e(TAG,"tempsocketsnotcreated",e);
}
mmInStream=tmpIn;
mmOutStream=tmpOut;
}
publicvoidrun(){
Log.i(TAG,"BEGINmConnectedThread");
byte[]buffer=newbyte[1024];
intbytes;
//KeeplisteningtotheInputStreamwhileconnected
while(true){
try{
//ReadfromtheInputStream
bytes=mmInStream.read(buffer);
//SendtheobtainedbytestotheUIActivity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ,bytes,
-1,buffer).sendToTarget();
}catch(IOExceptione){
Log.e(TAG,"disconnected",e);
connectionLost();
break;
}
}
}
/**
*WritetotheconnectedOutStream.
*
*@parambuffer
*Thebytestowrite
*/
publicvoidwrite(byte[]buffer){
try{
mmOutStream.write(buffer);
//SharethesentmessagebacktotheUIActivity
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE,-1,-1,
buffer).sendToTarget();
}catch(IOExceptione){
Log.e(TAG,"Exceptionduringwrite",e);
}
}
publicvoidcancel(){
try{
mmSocket.close();
}catch(IOExceptione){
Log.e(TAG,"close()ofconnectsocketfailed",e);
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。