I've been struggling with something recently and I can't move forward until it is properly handled. Here is my problem:
Description
I've been using a bluetooth inside my activity for a while now. I use it to communicate some data to a remote device. This communication is the most important part of my project since it sends and receives actions which modifies the user interface and possibly changes the configuration. I keep a UI-less fragment to contain the adapter. The adapter is created once when the fragment is itself created. Afterward, the fragment bypass the adapter creation if it already has an instance of it.
I do something like this:
BluetoothFragment.java:
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "Created");
setRetainInstance(true);
if(adapter == null) {
Log.e(TAG, "Creating a new bluetooth adapter");
adapter = new KBluetooth(new Messenger(mHandler));
}
super.onCreate(savedInstanceState);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Checks if the attaching activity implements KBluetoothCallback
try {
mHandler.setCallback((KBluetoothActivities) activity);
}
catch(ClassCastException castExc) {
throw new ClassCastException(activity.toString() + " must implement KBluetoothCallback");
}
}
Why I use this kind of implementation? because I don't want the Bluetooth adapter to reinitialize after a configuration change. Everything works fine until I press home button and come back to the activity. From that point, the fragment recreate a new adapter which means the adapter was null when the onCreate was run. I know it because I receive an error message in the log before creating the adapter.
My conclusion:
So here is my conclusion: even though the fragment is destroyed on a configuration change, my adapter is kept alive and instantiated but when the user press home, the fragment garbage every variables it contains. Am I right on that?
Question:
I need to keep a grip over the Bluetooth adapter even though the user is off the app. Anybody knows why this happens, or is there a user friendly way to avoid that kind of situation? In the case it isn't possible for me to avoid the data being destroyed when home is press, is there a way to distinguish between home and orientation change so I can safely disconnect the Bluetooth?
Note that the user can still back press and end the Bluetooth connection there, which is fine to me because he specifically said "I don't want this app running anymore".
Thank you in advance for your help. If you need more specifications, error messages or other stuff, feel free to ask.