XJQ124 / Some-notes

本仓库记录一些电脑方面的小技巧,包含各个方面
0 stars 0 forks source link

学习安卓蓝牙,目前进行到查找蓝牙设备 #2

Open XJQ124 opened 1 year ago

XJQ124 commented 1 year ago

任务:完成一个安卓遥控器(利用蓝牙实现)


任务链接: https://qgd5xm63s9.feishu.cn/sheets/CWcIsG9awhV0a8tj8KmcAr46nXc

1、今天在学习官方文档,目前进行到查找设备部分

首先要在项目中使用蓝牙功能,需要在配置文件中声明

    <!--声明蓝牙权限,BLUETOOTH是使用蓝牙的必备权限,第二个是管理员的蓝牙权限,一般仅用于“启动设备发现或操纵蓝牙设置”-->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>

    <!--获取位置权限,这里是把精准的权限和模糊的位置权限全都声明了-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

如上,是我使用蓝牙需要添加到部分

2、MainActivity中进行了如下操作

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_ENABLE_BT = 1;// 请求启用蓝牙的请求码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //在发现设备时注册广播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver,filter);

        //获取 BluetoothAdapter(也就是蓝牙无限装置),看看是否支持蓝牙
        BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
        } else {
            // 检查蓝牙权限
            if (checkSelfPermission(android.Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有蓝牙权限,请求蓝牙权限
                requestPermissions(new String[]{android.Manifest.permission.BLUETOOTH, android.Manifest.permission.BLUETOOTH_ADMIN}, REQUEST_ENABLE_BT);
            } else {
                // 蓝牙权限已授予,检查蓝牙是否已启用
            }
            //下面这个if是启用蓝牙的部分
            if (!bluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }else{
                //查询已配对的蓝牙设备信息  原因:这是有必要的,如果有的话,可以直接使用这个信息去连接
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

                if (pairedDevices.size() > 0) {
                    // There are paired devices. Get the name and address of each paired device.
                    for (BluetoothDevice device : pairedDevices) {
                        String deviceName = device.getName();
                        String deviceHardwareAddress = device.getAddress(); // MAC address
                    }
                }
            }
        }
    }
    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
            }
        }
    };
    @Override
    protected void onDestroy(){
        super.onDestroy();
        //注销 ACTION_FOUND receiver.
        unregisterReceiver(receiver);
    }
}

这部分基本上是跟着官网走的,所以没有遇见太大了的问题,解释一下上面

如何检查设备是否支持蓝牙
 //获取 BluetoothAdapter(也就是蓝牙无限装置),看看是否支持蓝牙
        BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
        } 
开启蓝牙
else {
            // 检查蓝牙权限
            if (checkSelfPermission(android.Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有蓝牙权限,请求蓝牙权限
                requestPermissions(new String[]{android.Manifest.permission.BLUETOOTH, android.Manifest.permission.BLUETOOTH_ADMIN}, REQUEST_ENABLE_BT);
            } else {
                // 蓝牙权限已授予,检查蓝牙是否已启用
            }
            //下面这个if是启用蓝牙的部分
            if (!bluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }

这里当时参考官网遇见一个问题,报错:Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException

大概意思是:你要用的这个权限,可能会被用户拒绝,所以代码上要给用户选择,具体方法已经写到上面

这是查询已配对蓝牙的信息
else{
                //查询已配对的蓝牙设备信息  原因:这是有必要的,如果有的话,可以直接使用这个信息去连接
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

                if (pairedDevices.size() > 0) {
                    // There are paired devices. Get the name and address of each paired device.
                    for (BluetoothDevice device : pairedDevices) {
                        String deviceName = device.getName();
                        String deviceHardwareAddress = device.getAddress(); // MAC address
                    }
                }
            }

为什么要有这一步?我之前也觉得我可能不会用到,因为你如果不写这个,第一次匹配以后,第二次用的时候不可能又去匹配吧,所以需要这个方法

这里是扫描蓝牙信息,查找设备
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
            }
        }
    };

同时,在发现设备时还需要注册广播

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver,filter);

最后,还要销毁这个接收器

  @Override
    protected void onDestroy(){
        super.onDestroy();
        //注销 ACTION_FOUND receiver.
        unregisterReceiver(receiver);
    }

明日任务:学习完官档,把其中一个app的框架搭好。