Android bluetooth connection doesn't close after application crash

前端 未结 2 1664
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 06:48

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

    Set devices = ba.getBondedDevices();
    for(BluetoothDevice bd : devices)
    {
         


        
相关标签:
2条回答
  • 2020-12-21 07:03

    I solved this problem by letting my BluetoothSockets be managed by a Service running in its own process. I open, close, read, and write the sockets by passing Messages to and from the Service. If the app crashes, the Service shuts down cleanly, closing the sockets. (It does not shut down cleanly if it's running in the same process as the app.)

    0 讨论(0)
  • 2020-12-21 07:10

    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- Store some socket identification that allow you to close it when app restarts.

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

    0 讨论(0)
提交回复
热议问题