Android:如何在未连接的情况下通过蓝牙发送内容时防止应用崩溃?

时间:2016-01-30 16:10:29

标签: android bluetooth

编辑:结果是它不会抛出IOException,而是抛出NullPointerException(因为outputStream为null)。在尝试从outputStream写入时,捕获它可以正常工作。

然而,当由于某种原因尝试从inputStream读取时,捕获NullPointerException不起作用,所以我在调用从inputStream读取的方法之前添加了一个check 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();}

然而它不起作用,烤面包不会显示并且它无论如何都会超时(如果没有可用的连接,它就不会像它一样永远循环)。

1 个答案:

答案 0 :(得分: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;
}

将始终为您提供最后一项,这可能会导致您搜索所需的完全不同的项目的问题。