android蓝牙app连接外设时崩溃问题

近期公司有蓝牙设备项目,遇到个问题;

连接蓝牙设备的app在连接时,如遇到蓝牙设备的信号名称错误或蓝牙设备关闭时,app有一定概率出现程序闪退;

经查证原因出现在接收蓝牙信号的广播的地方,原代码如下:

public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //g_Context.unregisterReceiver(this); ---deleted by jerry
            String action = intent.getAction();
            String strDevName = new String();
          
            if ( BluetoothDevice.ACTION_FOUND.equals(action) ) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                strDevName = device.getName();

                
                if ( strDevName.equalsIgnoreCase(bt_Name)) {
                    if( mBluetoothAdapter != null

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio是一款由Google开发的集成开发环境(IDE),用于开发Android应用程序。它提供了丰富的工具和功能,可以帮助开发者创建高质量的Android应用。 在Android Studio中,可以使用蓝牙API来实现与蓝牙设备的连接。以下是一般的蓝牙连接过程: 1. 添加权限:在AndroidManifest.xml文件中添加蓝牙权限,例如: ```xml <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> ``` 2. 初始化蓝牙适配器:通过BluetoothAdapter类获取蓝牙适配器对象,例如: ```java BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); ``` 3. 检查蓝牙状态:使用蓝牙适配器对象检查蓝牙是否可用,并请求打开蓝牙,例如: ```java if (bluetoothAdapter == null) { // 设备不支持蓝牙 } else { if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } ``` 4. 搜索蓝牙设备:使用蓝牙适配器对象进行设备搜索,并获取搜索到的设备列表,例如: ```java bluetoothAdapter.startDiscovery(); ``` 5. 连接蓝牙设备:通过BluetoothDevice类获取要连接蓝牙设备对象,并使用BluetoothSocket类进行连接,例如: ```java BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect(); ``` 6. 数据传输:通过输入输出流进行数据的读取和写入,例如: ```java InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); // 读取数据 byte[] buffer = new byte[1024]; int bytesRead = inputStream.read(buffer); // 写入数据 outputStream.write(data); ``` 以上是一般的蓝牙连接过程,具体实现还需要根据具体需求进行调整和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值