【问题标题】:Android: How to find out name of the bluetooth device connected?Android:如何找出连接的蓝牙设备的名称?
【发布时间】:2018-09-17 15:21:03
【问题描述】:

基本上我在这里尝试两件事,当我的蓝牙设备连接到特定设备时,我尝试开始敬酒(因此需要检查这是否是特定的蓝牙名称),如果那是特定设备,那么我想连接到该特定蓝牙设备时显示敬酒。当我的蓝牙与该特定蓝牙设备断开连接时,我还想举杯祝酒。 这是我的代码: 在 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 也可以工作,但连接的 toast 永远不会工作。

请告诉我为什么 CONNECTED toast 不起作用,以及如何使此代码在连接到特定设备时起作用(我不想为所有设备显示此 toast)。

【问题讨论】:

    标签: android bluetooth


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      相关资源
      最近更新 更多