Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

java - Android bluetooth connection doesn't close after application crash

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 :(

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...