2016-01-30 52 views
1

编辑:事实证明它不会抛出IOException,而是一个NullPointerException(因为outputStream为null)。当试图从outputStream写入时捕获它工作得很好。Android:如何在未连接时通过蓝牙发送内容时防止应用程序崩溃?

但是,当试图从inputStream中读取NullPointerException异常无法正常工作时,我只是在调用从inputStream读取的方法之前添加了一个检查if (inStream !=null)

那么,我解决了这个问题。


所以,我有一个应用程序,通过蓝牙连接到设备,并可以发送/接收字符串。

但是,可能会发生连接失败,无论是因为配对的设备已关闭还是因为设备未选取连接。在这种情况下,当我尝试发送一个字符串时,我的应用程序崩溃。

如何防止此次崩溃,而是显示敬酒并尝试重新连接?在IOException周围不会执行任何操作。

可能有用的代码:

方法来启动连接:

private void init() throws IOException { 


    if (blueAdapter != null) { 
     if (blueAdapter.isEnabled()) { 
      Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices(); 

      if(bondedDevices.size() > 0){ 
       BluetoothDevice bt2 = null; 
       for(BluetoothDevice bt : bondedDevices) { 
        bt2 = bt; 
       } 


       BluetoothDevice device = bt2; 
       ParcelUuid[] uuids = device.getUuids(); 
       BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid()); 
       socket.connect(); 
       outputStream = socket.getOutputStream(); 
       inStream = socket.getInputStream(); 
      } 

      Log.e("error", "No appropriate paired devices."); 
     }else{ 
      Log.e("error", "Bluetooth is disabled."); 
     } 
    } 
} 

方法写入字符串:

public void write(String s) throws IOException { 
    outputStream.write(s.getBytes()); 
} 

代码写入字符串:

try { 
    write(string); 
} catch (IOException e1) { 
    Toast.makeText(getBaseContext(), "Couldn't send the code.", Toast.LENGTH_SHORT).show(); 
} 

编辑:我试图在init方法中添加一个检查:

if (!socket.isConnected()) { 
    toast("Couldn't connect. Reconnecting..."); 
    init();} 

但是它不工作,敬酒不显示和超时反正(不循环永远像它会做,如果没有可用的连接)。

+0

定义三个不同蓝牙设备参考的目的是什么?你也可以添加你的错误logcat到你的问题? –

+0

我不知道,我只是从https://wingoodharry.wordpress复制/粘贴代码。com/2014/03/16/simple-android-to-arduino-via-bluetooth-part-3 /,与我在其他几个地方找到的代码混合在一起。然而,它工作得很好,所以我不认为这是事实。至于logcat我没有它,ADB不能识别我的设备,仿真器太滞后了。 – Zezombye

+0

如果adb无法识别您的设备,那么您如何运行该应用程序? –

回答

0

更换你socket.connect()连接与

while(true){ 
    try { 
     socket.connect(); 
     //When we are here the connection suceeded 
    }catch (Exception e){ 
     //The connection failed 
    } 
} 

不过要小心在UI线程不运行这个,因为这将阻止线程,使您的应用程序没有响应。而是创建一个搜索器线程,然后回调它发现的东西。

你不需要行

BluetoothDevice device = bt2; 

只是BT2在你的代码替换设备并删除该行。 也请注意,你的循环

for(BluetoothDevice bt : bondedDevices) { 
    bt2 = bt; 
} 

将永远给你的最后一个项目,这可能导致你寻找你想要一个完全不同的项目的问题。

相关问题