문제

I'm creating an app that has a bluetooth connection. I've created a library that uses callbacks every time a connection is lost/failed/established/etc. Everything about the connection works just fine, but I'm having a hard time handling orientation changes. I want the connection to remain open when the device changes orientation. At the same time I want the connection to close when the user closes the application. The API levels I'm designing this for are APIs 5-10. Here's the issues I come across:

  1. If I close my connection on onDestroy(), the connection will close every time the app is closed but not when the app is simply paused (desired output). However, onDestroy() is called whenever the application orientation changes. Which leads to issue #2.

  2. If I use onRetainNonConfigurationInstance(), I can successfully keep the open socket. If I don't close the socket in onDestroy(), then everything works just fine. However, the socket seems to remain open when the app closes (i.e. the other devices are still reading from it).

The setup I currently have looks similar to this:

BluetoothConnection btConnection;
@Override
public void onCreate(Bundle icicle)
{
   /** Activity setup **/

   btConnection = (BluetoothConnection) getLastNonConfigurationInstance();
   if(btConnection != null) // we already have a connection from a previous state, let's set it up to work with this state
   {
      /** Set up the connection since it already exists **/
   }
}

@Override
public Object onRetainNonConfigurationInstance()
{
   BluetoothConnection saveConnection = btConnection;
   return saveConnection;
}

@Override
protected void onDestroy()
{
   super.onDestroy()
   if(btConnection != null)
      btConnection.closeConnection();
}

With this current implementation, the socket will be saved but closed at the same time because both onRetainNonConfigurationInstance() is called as well as onDestroy().

I guess I'd like to know two things:

  1. Is onRetainNonConfigrationInstance() a good way to handle this problem to begin with?
  2. Is there a more elegant way to keep a connection open till an app closes? I've thought about creating a boolean like onRetainCalled to prevent the thing from closing, but it seems ugly to me (and possibly unreliable).
도움이 되었습니까?

해결책

Optimally, you should put your Bluetooth connection code into a Service: I use this and it is quite excellent. You can open multiple Activities without having to think about it at all.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top