Android 蓝牙开发详述
转自:http://blog.csdn.net/einarzhang/article/details/6943861在AndroidSDK sample中给出了一个蓝牙聊天的示例代码,本文只是略作修改变成一个简单的服务器和客户端模式的应用,以适应在游戏开发中一对一关联的数据传输。由于游戏中的蓝牙设置在新线程中发生,所以采用Handler的方式将蓝牙的状态以及读取信息传输给显...
·
转自:http://blog.csdn.net/einarzhang/article/details/6943861
在AndroidSDK sample中给出了一个蓝牙聊天的示例代码,本文只是略作修改变成一个简单的服务器和客户端模式的应用,以适应在游戏开发中一对一关联的数据传输。
由于游戏中的蓝牙设置在新线程中发生,所以采用Handler的方式将蓝牙的状态以及读取信息传输给显示Activity。
1 开启蓝牙,包括xml中的配置:
- <uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"/>
- <uses-permissionandroid:name="android.permission.BLUETOOTH"/>
- //获取蓝牙适配器
- BluetoothAdapterbtAdapter=BlueToothService.getInstance().getBtAdapter();
- //开启蓝牙
- if(!btAdapter.isEnabled()){
- IntentenableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableIntent,ConstantsUtil.ENABLE_BLUETOOTH);
- }
2 在当前Activity中获取蓝牙开启结果,并根据具体情况对蓝牙进行处理
- @Override
- protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
- switch(requestCode){
- caseConstantsUtil.ENABLE_BLUETOOTH:
- if(resultCode==Activity.RESULT_OK){
- bluetoothProcess(PSystem.isServer);
- }else{
- finish();
- }
- }
- }
- publicvoidbluetoothProcess(booleanisServer){
- BlueToothService.getInstance().setsHandler(mHandler);
- if(isServer){
- //如果是蓝牙服务器,则需要开启发现服务,并启动蓝牙服务器
- if(btAdapter.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
- IntentdiscoverableIntent=newIntent(
- BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- discoverableIntent.putExtra(
- BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,180);
- startActivity(discoverableIntent);
- }
- BlueToothService.getInstance().start();
- }else{
- //如果是蓝牙客户端则扫描周围可用的蓝牙设备
- blueToothNames=newArrayList<String>();
- blutToothDevices=newArrayList<BluetoothDevice>();
- //添加过滤器,并注册广播,用于监听蓝牙发现信息
- IntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
- this.registerReceiver(mReceiver,filter);
- filter=newIntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
- this.registerReceiver(mReceiver,filter);
- //开始扫描
- doDiscovery();
- }
- }
- publicvoiddoDiscovery(){
- if(btAdapter.isDiscovering()){
- btAdapter.cancelDiscovery();
- }
- btAdapter.startDiscovery();
- }
3 蓝牙广播接收器
- privatefinalBroadcastReceivermReceiver=newBroadcastReceiver(){
- @Override
- publicvoidonReceive(Contextcontext,Intentintent){
- Stringaction=intent.getAction();
- if(BluetoothDevice.ACTION_FOUND.equals(action)){
- BluetoothDevicedevice=intent
- .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- if(device.getName()!=null&&!device.getName().trim().equals("")){
- blueToothNames.add(device.getName());
- blutToothDevices.add(device);
- }
- }elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED
- .equals(action)){
- btAdapter.cancelDiscovery();
- TestActivity.this.unregisterReceiver(this);
- }
- }
- };
4 以上是蓝牙基本配置和发现。现在进行蓝牙监听和连接:
蓝牙服务器监听代码:
- publicvoidstart(){
- BluetoothServerSocketserverSocket=null;
- try{
- serverSocket=btAdapter.listenUsingRfcommWithServiceRecord("JumpForMeApp",MY_UUID_SECURE);
- changeState(ConstantsUtil.BT_STATE_LISTEN);
- btSocket=serverSocket.accept();
- }catch(IOExceptione){
- }finally{
- try{
- serverSocket.close();
- }catch(IOExceptione){
- }
- }
- if(btSocket!=null){
- changeState(ConstantsUtil.BT_STATE_CONNECTED);
- }
- }
客户端连接代码:
- publicvoidconnect(BluetoothDevicedevice){
- try{
- btAdapter.cancelDiscovery();
- btSocket=device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
- changeState(ConstantsUtil.BT_STATE_CONNECTING);
- btSocket.connect();
- }catch(IOExceptione){
- }
- changeState(ConstantsUtil.BT_STATE_CONNECTED);
- }
5利用蓝牙进行消息传递,建立新的线程来处理读写操作(见BluetoothChat Sample中的ConnectedThread):
- classConnectedThreadextendsThread{
- privatefinalBluetoothSocketmmSocket;
- privatefinalInputStreammmInStream;
- privatefinalOutputStreammmOutStream;
- publicConnectedThread(BluetoothSocketsocket){
- mmSocket=socket;
- InputStreamtmpIn=null;
- OutputStreamtmpOut=null;
- try{
- tmpIn=socket.getInputStream();
- tmpOut=socket.getOutputStream();
- }catch(IOExceptione){
- Log.e(TAG,"tempsocketsnotcreated",e);
- }
- mmInStream=tmpIn;
- mmOutStream=tmpOut;
- }
- publicvoidrun(){
- byte[]buffer=newbyte[1024];
- intbytes;
- while(true){
- try{
- bytes=mmInStream.read(buffer);
- if(transHandler!=null){
- //通知数据传输处理器
- transHandler.sendMessage(transHandler.obtainMessage(ConstantsUtil.BT_READ,bytes,-1,buffer));
- }
- }catch(IOExceptione){
- Log.e(TAG,"disconnected",e);
- break;
- }
- }
- }
- publicvoidwrite(byte[]buffer){
- try{
- mmOutStream.write(buffer);
- }catch(IOExceptione){
- Log.e(TAG,"Exceptionduringwrite",e);
- }
- }
- publicvoidcancel(){
- try{
- mmSocket.close();
- }catch(IOExceptione){
- Log.e(TAG,"close()ofconnectsocketfailed",e);
- }
- }
- }
更多推荐
已为社区贡献5条内容
所有评论(0)