我有一个Fragment
,其中我引用了BluetoothConnection
类。在BluetoothConnection
我处理通过其他蓝牙设备连接所需的所有内容。所有工作正常,但当我旋转我的设备连接消失。那么如何保存配置更改的连接?我用片段作为setRetainInstance(true)
方法阅读,但它只跳过onCreate
方法。我知道我可以将所有BluetoothConnection
移到Service
但我认为这不是一个好的解决方案。这是我的代码:
private BluetoothConnection connection = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Log.d(TAG, "onCreate");
//setRetainInstance(true);
adapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (adapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
bindService();
}
@Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!adapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (connection == null) {
setupChat();
}
Log.d(TAG, "onStart");
}
private void setupChat() {
if(!isConnected){
button.setEnabled(false);
}
command = new CommandFormatter();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean turnOn = ((ToggleButton) v).isChecked();
if (isConnected) {
if (turnOn) {
formatCommand("On");
sendCommand(command.generateXML());
} else {
formatCommand("Off");
sendCommand(command.generateXML());
//isConnected = false;
}
}
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
connection = new BluetoothConnection(handler);
}