android 藍芽操作,主要解決connect失敗

來源:互聯網
上載者:User

關於藍芽操作的例子我這裡就不多說的。網上一搜一大堆,但是通常都是按照官方提供的SDK上的api進行開發的。

我剛開始做開發的時候也是用的官方api,但是會出現很多奇怪的問題,最主要的就是同一段代碼在不同機器上跑,有的機器正常,有的機器會拋異常。

為此,我搜了很多方法,最主要的就是利用java的反射機制。

關於反射機制 可以參考這片blog http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html

藍芽通訊跟一般socket通訊非常相似,都是建立一個服務通訊端,然後用戶端來建立串連。我這裡就不講解用官方的UUID的方式來建立了。

這裡採用了反射機制。。

服務端:

try {Method mthd = adp.getClass().getMethod("listenUsingRfcommOn",new Class[] { int.class });try {ss = (BluetoothServerSocket) mthd.invoke(adp,new Object[] { 29 });java.lang.System.out.println("建立服務通訊端成功");playThread.start();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();}// ss = adp.listenUsingInsecureRfcommWithServiceRecord("suixiang",// MY_UUID);  //官方api

用戶端:

// BluetoothSocket s = device// .createInsecureRfcommSocketToServiceRecord(BluetoothActivity.MY_UUID);// s.connect();   //官方apiBluetoothSocket s = null;try {System.out.println("開始串連");Method method = device.getClass().getMethod("createRfcommSocket",new Class[] { int.class });try {s = (BluetoothSocket) method.invoke(device,new Object[] { 29 });s.connect();System.out.println("串連成功");} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();}

通過這種方式建立的串連比較穩定。。歡迎交流。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.