当前位置: 动力学知识库 > 问答 > 编程问答 >

Android : How to execute code when bluetooth connection disconnected to particular device

问题描述:

I wanna know how to execute a particular code when my fone's bluetooth device is connected to any device and also i want to execute another code when my fone disconnects from that bluetooth connection?

Please provide the code with proper comments.

网友答案:

You can create a BroadcastReceiver to handle that:

In on 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>  

Write class MyBluetoothReceiver derived from BroadcastReceiver. Override the onReceive method and for each action implement your code:

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;
        }
    }
}
网友答案:

Here's the proper answer I found :

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)) {

    }
}
};
分享给朋友:
您可能感兴趣的文章:
随机阅读: