应用程序崩溃后,Android 蓝牙连接不会关闭 [英] Android bluetooth connection doesn't close after application crash

查看:25
本文介绍了应用程序崩溃后,Android 蓝牙连接不会关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SPP 配置文件连接到我的设备:

i'm using SPP profile for connect to my device:

    Set<BluetoothDevice> devices = ba.getBondedDevices();
    for(BluetoothDevice bd : devices)
    {
        String name = bd.getName();
        if(name.equals("CELLMETER"))
        {
            try
            {
                BluetoothSocket bs = bd.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                bs.connect();
            } catch (IOException e)
            {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }

看起来一切正常,我创建了关闭输入输出缓冲区和关闭套接字的函数.但是,当应用程序崩溃或我在断点到达时停止应用程序时,套接字不会关闭,即使在我手动终止进程之后,它也无法用于来自应用程序新实例的新连接.

All seems okay, i created function where i'm closing input output buffers and close socket. But when application crashes or i'm stopping application when breakpoints arrives socket doesn't closes, even after i kill process manually and it's not avalible for new connection from new instance of app.

我做错了什么?对于每个崩溃/调试操作,我必须重新启动手机:(

What i'm doing wrong? For each crash/debug operation i have to reboot phone :(

它仅在 Android 2.3.5 (Samsung 5830i) 和 Android 4.0.4 (Freelander P10) 上体现.在我的 Android 4.2.1 (Galaxy Nexus) 上一切正常,应用程序崩溃后连接自动关闭.(似乎是因为有新的蓝牙堆栈)

It's manifested only to Android 2.3.5 (Samsung 5830i) and on Android 4.0.4 (Freelander P10). On my Android 4.2.1 (Galaxy Nexus) all okay, after app crash connection closes automatically. (it seems because there is new Bluetooth stack)

推荐答案

我可以看到 2 个选项来解决这个问题:1- 在您的应用程序中添加一个 UncaughtExceptionHandler,最好在应用程序派生类中:

I can see 2 options to work that out: 1- Add an UncaughtExceptionHandler in your app, best in Application-derived class:

        mUEHandler = new Thread.UncaughtExceptionHandler()
        {
            @Override
            public void uncaughtException(Thread t, Throwable e)
            {
                // Close any opened sockets here

                defaultUEH.uncaughtException(t, e);
            }
        };

        Thread.setDefaultUncaughtExceptionHandler(mUEHandler);

但这只会处理应用程序崩溃.如果用户杀死应用程序,则根本无法进入.

But that only takes care of app crashes. If user kills the app, won't get in there at all.

2- 存储一些套接字标识,允许您在应用程序重新启动时关闭它.

2- Store some socket identification that allow you to close it when app restarts.

它并不完美,但可以解决您的问题.

It's not perfect, but that could work-around your issue.

这篇关于应用程序崩溃后,Android 蓝牙连接不会关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆