安卓:如何查找已连接蓝牙设备的名称?

5

我这里想实现两个功能,第一个是在我的蓝牙设备连接到特定设备时启动一个提示框(需要检查是否为特定的蓝牙名称),如果是该特定设备,则显示一个提示框。第二个是当我的蓝牙与该特定蓝牙设备断开连接时显示一个提示框。 以下是我的代码: 在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>  

类的代码:

public class MyBluetoothReceiver extends BroadcastReceiver {

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

         Toast.makeText(context, "RECEIVER CALLED!!", Toast.LENGTH_LONG).show();


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

           // code for Bluetooth connect

           Toast.makeText(context, "CONNECTED!!", Toast.LENGTH_LONG).show();
        }

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

          //code for Bluetooth disconnect;
          Toast.makeText(getApplicationContext(),"DISCONNECTED",Toast.LENGTH_LONG).show();
        }
    }
}

在我的代码中,我已经正确地调用了接收器并且连接断开的toast也能正常工作,但是连接成功的toast从未起作用。请告诉我为什么 CONNECTED toast 不起作用,如何使得该代码只对特定设备连接时生效(我不想对所有设备都显示该toast)。

1个回答

7

将您的广播接收器更改为:

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

        }
    }
 };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接