【问题标题】:Android: How to prevent app crash when sending something via bluetooth while not connected?Android:如何在未连接时通过蓝牙发送内容时防止应用程序崩溃?
【发布时间】:2016-01-30 16:10:28
【问题描述】:

编辑:原来它没有抛出 IOException,而是抛出 NullPointerException(因为 outputStream 为空)。尝试从 outputStream 写入时,捕获它就可以正常工作。

但是,当出于某种原因尝试从 inputStream 读取时,捕获 NullPointerException 不起作用,因此我只是在调用从 inputStream 读取的方法之前添加了一个检查 if (inStream !=null)。

好吧,我解决了这个问题。


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

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

如何防止这种崩溃,而是显示一个 toast 并尝试重新连接?用 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();}

但是它不起作用,toast 不显示并且无论如何都会超时(不会像没有可用连接时那样永远循环)。

【问题讨论】:

  • 定义三个不同的蓝牙设备引用的目的是什么?您也可以将错误的日志添加到您的问题中吗?
  • 我不知道,我只是从wingoodharry.wordpress.com/2014/03/16/… 复制/粘贴代码,并与我在其他几个地方找到的代码混合。但是它工作得很好,所以我不认为是这样。至于logcat我没有,ADB不识别我的设备,模拟器太卡了。
  • 如果 adb 无法识别您的设备,您如何运行应用程序?
  • 我手动将apk传输到手机,然后通过文件资源管理器运行
  • 听起来你只需要在手机上启用usb调试

标签: android bluetooth


【解决方案1】:

将你的 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;
}

将始终为您提供最后一个项目,这可能会导致您无法搜索完全不同的项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多