从Android设备连接到嵌入式蓝牙设备

pra*_*een 7 android

我刚刚开始通过我的Android手机连接到嵌入式BT设备.它连接正常,但我正面临问题,当我没有正确断开连接.我的意思是先关闭套接字,然后打开任何i/o流.

但是当我在设备中突然关闭我的蓝牙时,我怎么知道蓝牙会断开连接.是否有任何方法可以在APP中随时接收蓝牙断开监听器.

有任何想法吗 ....?谢谢

mmSocket= device.createRfcommSocketToServiceRecord(uuidToTry);
try
{
    mmSocket.connect();
}
catch (IOException e)
{
    mmSocket.close();
}
Run Code Online (Sandbox Code Playgroud)

shr*_*ari 1

您可以这样做 - 在代码中创建广播接收器,如下所示:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (!mBluetoothAdapter.isEnabled()) {
                // BT is turened off.
            }
            else{
                // BT is turened on.
              }
        }
 }
};
Run Code Online (Sandbox Code Playgroud)

并为以下意图过滤器注册该广播接收器:

IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mReceiver, filter);