之后,应用程序崩溃的Andr​​oid蓝牙连接不关闭蓝牙、应用程序、Andr、oid

2023-09-07 15:26:24 作者:繁华落尽相思绝

我使用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.
            }
        }
    }

所有看起来不错,我创建功能,其中我关闭输入输出缓冲器,并关闭套接字。 但是,当应用程序崩溃或者说我停止应用程序时,断点到达套接字不关闭,我手动杀进程,它不是avalible从应用程序的新实例,新的连接,即使。

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(三星5830i),并在Android 4.0.4(神行者P10)。在我的Andr​​oid 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.