9

我正在制作一个使用蓝牙连接的应用程序。我打电话onCreate()蓝牙连接和onDestroy()MainActivity的关闭它:如何在Android中关闭BluetoothSocket的屏幕旋转功能?

// Bluetooth 
private Bluetooth bt; 
private boolean registered = false; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    bt = new Bluetooth(this); 
    bt.enableBluetooth(); 
    bt.setCommunicationCallback(this); 
    bt.connectToName(bt.getBluetoothDevice(this)); 
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); 
    registerReceiver(mReceiver, filter); 
    registered = true; 
} 

@Override  
public void onDestroy() { 
    super.onDestroy(); 
    if(registered) { 
     unregisterReceiver(mReceiver); 
     registered=false; 
    } 
    bt.removeCommunicationCallback(); 
    bt.disconnect(); 
    if (handler != null && runnable != null) { 
     handler.removeCallbacks(runnable); 
    } 
} 

该应用程序还支持(使用两种不同的布局)风景和肖像模式。当屏幕被旋转时,MainActivity调用onCreate()onDestroy功能,由于不同的布局。出于这个原因,我得到了以下错误:

@@@ ABORTING: INVALID HEAP ADDRESS IN dlfree addr=0x5a71aa38 
A/libc: Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 1051 (le.bluetoothled) 

正如我在Invalid heap address and fatal signal 11发现,它是从的BluetoothSocket的close()方法。首先,我认为我们不需要关闭蓝牙,当我们旋转屏幕,因此,我试图用该方法来电话的detect rotation event而忽略关闭时的旋转发生,但是,这是行不通的。因此,我认为当屏幕旋转时我们可能需要关闭蓝牙,但是我得到了上述错误。我不知道我该如何解决这个问题,你能帮我解决这个问题吗?我使用this蓝牙LIB与disconnect()如下:

public void disconnect() { 
     try { 
      socket.close(); 
     } catch (IOException e) { 
      if(communicationCallback!=null) 
       communicationCallback.onError(e.getMessage()); 
     } 
    } 

由于我目前的解决方案是使用睡眠。我在关闭套接字前添加了Thread.sleep (1000)。这是工作。但我认为这不是一个很好的解决方案。

+0

你是什么'Bluetooth'类?这是“服务”吗? – Bryan

+0

号这只是正常的类作为https://github.com/omaflak/Bluetooth-Library/blob/master/bluetooth/src/main/java/me/aflak/bluetooth/Bluetooth.java – Jame

+0

会发生什么事的时候一个您为蓝牙连接创建的线程仍在运行,您旋转设备?他们继续参考旧的活动。您正在尝试清除对活动回调的引用,但如果它为空,您还会检入另一个线程。这是不安全的。 – masp

回答

0

您可以在活动中添加Fragment并调用setRetainInstnce这个片段来处理方向的变化。用蓝牙将您的逻辑移动到Fragment。看看如何实现这个herehere

+0

这不好。其实,我试图解决以上错误 – Jame

0

试试这个代码

@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
    //disconnect your bluetooth 
} 
+0

这不好。其实,我正试图解决上述错误 – Jame

0

添加此标记在受人尊敬的活动代码清单文件。 添加此标签中推崇的活动来体现后,活动可以保留方向的onDestroy()不叫和蓝牙接口未关闭的状态和变化的过程中。

机器人:configChanges = “keyboardHidden |方向|屏幕尺寸”

1

你绝不能使用蓝牙 - 内部活动相关的东西(见固体)的原则。活动只是一个用户界面。您应该创建单独的服务,它将独立于后台的用户界面运行,并管理所有与蓝牙相关的操作。从您的Activity绑定到onResume()方法中的该服务,并在onPause()方法中解除绑定。您可以从ServiceConnection获取bt-控制接口,并在绑定期间通过服务传递。 谷歌有一个伟大的蓝牙例子 - https://github.com/googlesamples/android-BluetoothChat。唯一的缺点 - 它使用Handler传递消息。我修改了它 - 现在有另一个线程,接收所有状态消息并调用回调。随意使用此代码: https://github.com/AlexShutov/LEDLights