Android学习之Bluetooth开发总结<续>
2013-07-18 17:05
483 查看
private class ConnectThread extends Thread { private BluetoothSocket mmSocket; private BluetoothDevice mmDevice; ImprovedBluetoothDevice improvedBluetoothDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; improvedBluetoothDevice = new ImprovedBluetoothDevice(device); } public void run() { Log.i(TAG, "BEGIN mConnectThread"); //setName("ConnectThread"); // Always cancel discovery because it will slow down a connection //蓝牙连接之前需要取消查找 mAdapter.cancelDiscovery(); //String connectionType = "?"; //蓝牙设备有三十个端口号,是从1到30 for(int port = 1; port < 31; port++) { Log.d(TAG, "Connecting with port: " + port); try { //connectionType = "Secure"; Log.d(TAG, "Attempting createRfcommSocket"); //分别使用1-30这些端口 BluetoothSocket s = improvedBluetoothDevice.createRfcommSocket(port); s.connect(); mmSocket = s; } catch (Exception ex) { Log.e(TAG, ex.toString()); //TODO 异常处理 //赋值为空 mmSocket = null; try { //connectionType = "Insecure"; Log.d(TAG, "Attempting createInsecureRfcommSocket"); //如果在连接过程中出现异常,就使用第二种方案来进行连接 BluetoothSocket s = improvedBluetoothDevice.createInsecureRfcommSocket(port); s.connect(); mmSocket = s; } catch (Exception ex2) { Log.e(TAG, ex2.toString()); //异常处理 //如果再次连接还是出异常,就再次赋值为空 mmSocket = null; } } if (mmSocket != null) { Log.d(TAG, "Connection succeeded with " + connectionType + " connection on port " + port); break; } } //如果还没有获取到mmSocket ,就使用以下方法 //蓝牙串口连接有两种方式,一种是使用端口号,另一种是使用UUID,如果1-30的端口号都不能连接上,就使用UUID进行连接 if (mmSocket == null) { try { mmSocket = improvedBluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID); mmSocket.connect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Reset the ConnectThread because we're done //synchronized (BluetoothChatService.this) { //mConnectThread = null; //} // Start the connected thread //connected(mmSocket, mmDevice); } public void cancel() { try { if(mmSocket!=null) { mmSocket.close(); mmSocket = null; } } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } }
相关文章推荐
- Android学习之Bluetooth开发总结<续3>
- Android学习之Bluetooth开发总结<续2>
- Android学习之多线程开发总结<三>
- Android学习之多线程开发总结<二>
- Android学习之多线程开发总结<一>
- Android <Android应用开发实战> 学习总结杂项
- <<Android源码设计模式解析与实战>>读书笔记----- Android NDK开发学习
- 3G之Android学习第一章节<<开发环境搭建>>
- <转>二十六个月Android学习工作总结(2013-05-02更新)
- Android 数据库ORM框架GreenDao学习心得及使用总结<一>
- 3G之Android学习第二章节<<开发第一个HelloWorld应用程序>>
- 【Android开发学习45】使用google语音识别引擎(Google Speech API)<一>
- 【Android开发学习45】使用google语音识别引擎(Google Speech API)<一>
- Android学习之Bluetooth开发总结
- Android学习之Bluetooth开发总结
- Android 数据库ORM框架GreenDao学习心得及使用总结<二>
- android WebView开发总结<续>
- android <初级篇> 开发环境的搭建——菜鸟的学习之路
- C和C++语言学习总结(资料来自<高质量C++/C 编程指南> 林锐博士 2001 年7 月24)
- Android学习总结(1)——好的 Android 开发习惯