Android:如何在蓝牙连接断开连接到特定设备时执行代码

时间:2014-01-07 18:24:19

标签: android bluetooth

我想知道当我的fone的蓝牙设备连接到任何设备时如何执行特定的代码,并且当我的fone断开与蓝牙连接的连接时我还想执行另一个代码? 请提供适当的评论代码。

2 个答案:

答案 0 :(得分:0)

您可以创建一个BroadcastReceiver来处理:

在manifest.xml上:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<receiver android:name=".MyBluetoothReceiver" >
    <intent-filter>
        <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
        <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
        <action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />           
    </intent-filter>  
</receiver>  

编写从BroadcastReceiver派生的类MyBluetoothReceiver。覆盖onReceive方法,并为每个操作实现代码:

public class MyBluetoothReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals(
          "android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED")){

           // code for Bluetooth connect
        }

        if(intent.getAction().equals(
          "android.bluetooth.device.action.ACL_DISCONNECTED")){

          //code for Bluetooth disconnect;
        }
    }
}

答案 1 :(得分:0)

这是我找到的正确答案:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
       String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent
                .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                      //you can get name by device.getName()

    } else if (BluetoothAdapter.ACL_DISCONNECTED
            .equals(action)) {

    }
}
};