Android 查找和连接蓝牙功能开发问题

在开发蓝牙功能的时候在网上下了一个demo,demo代码移植在我的一个测试项目上是完全可以查找和连接的,但是吧代码移植到我的正式工程的时候总是不行不知道怎么回事(报错信息在网上也不好找到解决原因),这里有这方面熟悉的朋友帮忙看下,如果如推荐的demo可以参考更为感谢

下面上代码和报错信息

查找蓝牙方法

 public void searchBlueToothDevice() {

        //Log.i(TAG, "searchBlueToothDevice(MainActivity.java:112)--->> " + "searchBlueToothDevice");

        pdSearch = ProgressDialog.show(StockOutScan.this, "", "连接中", true, true);
        pdSearch.setCanceledOnTouchOutside(false);
        pdSearch.show();

        mBluetoothList = new ArrayList<BluetoothBean>();
        // 检查设备是否支持蓝牙
        Bluetoothadapter = BluetoothAdapter.getDefaultAdapter();
        if (Bluetoothadapter == null) {
            Toast.makeText(this, "当前设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        // 如果蓝牙已经关闭就打开蓝牙
        if (!Bluetoothadapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(intent);
            return;
        }
//        // 获取已配对的蓝牙设备
//        Set<BluetoothDevice> devices = adapter.getBondedDevices();
//        // 遍历
//        int count = 0;
//        for (BluetoothDevice pairedDevice : devices) {
//            Log.i(TAG, "searchBlueToothDevice(MainActivity.java:137)--->> " + pairedDevice.getName());
//            if (pairedDevice.getName() == null) {
//                return;
//            } else if (pairedDevice.getName().startsWith("Printer_29D0")) {
//                count++;
//                deviceAddress = pairedDevice.getAddress();
//                mBluetoothDevice = adapter.getRemoteDevice(deviceAddress);
//                connect(deviceAddress, mBluetoothDevice);
//                break;
//            }
//        }

        if (Bluetoothadapter.isEnabled()) {
            //开始搜索
            Bluetoothadapter.startDiscovery();

            // 设置广播信息过滤
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            // 注册广播接收器,接收并处理搜索结果
            receiver = new MyBroadcastReceiver();
            registerReceiver(receiver, intentFilter);
        }
    }

广播代码

 public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //找到设备,有可能重复搜索同一设备,可在结束后做去重操作
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device == null) {
                    return;
                }
                if (device.getName() == null) {
                    return;
                }

                BluetoothBean bluetoothBean = new BluetoothBean();
                bluetoothBean.mBluetoothName = device.getName();
                bluetoothBean.mBluetoothAddress = device.getAddress();
                bluetoothBean.mBluetoothDevice = Bluetoothadapter.getRemoteDevice(bluetoothBean.mBluetoothAddress);
                mBluetoothList.add(bluetoothBean);

                //Log.i(TAG, "onReceive(MainActivity.java:184)--->> " + device.getName());
                //Log.i(TAG, "onReceive(MainActivity.java:185)--->> " + mBluetoothList.size());

//                if (device.getName().startsWith("Printer_29D0")) {
//                    //取消搜索
//                    adapter.cancelDiscovery();
//                    deviceAddress = device.getAddress();
//                    mBluetoothDevice = adapter.getRemoteDevice(deviceAddress);
//                    connectState = device.getBondState();
//                    switch (connectState) {
//                        // 未配对
//                        case BluetoothDevice.BOND_NONE:
//                            // 配对
//                            try {
//                                Method createBondMethod = mBluetoothDevice.getClass().getMethod("createBond");
//                                createBondMethod.invoke(mBluetoothDevice);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                            break;
//                        // 已配对
//                        case BluetoothDevice.BOND_BONDED:
//                            if (device.getName().startsWith("Printer_29D0")) {
//                                connect(deviceAddress, mBluetoothDevice);
//                            }
//                            break;
//                    }
//                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //Log.i(TAG, "onReceive(MainActivity.java:213)--->> " + "搜索完成");
                pdSearch.dismiss();
                if (0 == mBluetoothList.size())
                    Toast.makeText(StockOutScan.this, "搜索不到蓝牙设备", Toast.LENGTH_SHORT).show();
                else {
                    //去重HashSet add会返回一个boolean值,插入的值已经存在就会返回false 所以true就是不重复的
                    HashSet<BluetoothBean> set = new HashSet<BluetoothBean>();
                    mBluetoothList2 = new ArrayList<BluetoothBean>();
                    for (BluetoothBean bean : mBluetoothList) {
                        boolean add = set.add(bean);
                        if (add) {
                            mBluetoothList2.add(bean);
                        }
                    }
                    showBluetoothPop(mBluetoothList2);
                }

                unregisterReceiver(receiver);
            }
        }
    }


弹框显示搜索到的蓝牙

 //弹框显示蓝牙设备
     private void showBluetoothPop(final List<BluetoothBean> bluetoothList) {
         bluetoothtitle = (TextView) dialogView.findViewById(R.id.bluetooth_btitle);
         bluetoothlistview = (ListView) findViewById(R.id.bluetooth_listview);
         if (myBluetoothAdapter == null) {
                myBluetoothAdapter = new MyBluetoothAdapter(
                        StockOutScan.this,bluetoothList);
            }
            bluetoothlistview.setAdapter(myBluetoothAdapter);

            // 弹出对话框
            bluetoothtitle.setText("选择连接蓝牙");
            // 根据listview高度刷新弹框高度
            refreshHeight(bluetoothlistview);
     }

报错信息在注册广播方法哪一步

图片说明

图片说明
上图是蓝牙的权限
图片说明
上图是我移植到我的测试工程里运行后的结果是正常的

// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
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_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // If it's already paired, skip it, because it's been listed already
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                if(StringUtil.isNotBlank(device.getName())){
                    DeviceItem item = new DeviceItem();
                    item.setName(device.getName());
                    item.setAddress(device.getAddress());
                    item.setDevice(device);
                    mNewDevicesList.add(item);
                    mNewDevicesArrayAdapter.setData(mNewDevicesList);
                    mNewDevicesArrayAdapter.notifyDataSetChanged();
                }
            }
        // When discovery is finished, change the Activity title
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            if (mNewDevicesList.size() == 0) {
                DeviceItem item = new DeviceItem();
                item.setName("没有找到设备");
                item.setAddress("");
                mNewDevicesList.add(item);
                mNewDevicesArrayAdapter.setData(mNewDevicesList);
                mNewDevicesArrayAdapter.notifyDataSetChanged();
            }
            scanButton.setText("扫描");
        } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){ // 远程设备的连接状态改变
            BluetoothDevice stateChangeDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.e(Constant.PRINT_TAG, "蓝牙设备的状态" + stateChangeDevice.getBondState());
            switch (stateChangeDevice.getBondState()) {
                case BluetoothDevice.BOND_BONDING:
                    ToastUtil.toast("正在配对......");
                    Log.e(Constant.PRINT_TAG, "正在配对......");
                    break;
                case BluetoothDevice.BOND_BONDED:
                    ToastUtil.toast("完成配对");
                    Log.e(Constant.PRINT_TAG, "完成配对");
                    initPairedDevicesList();
                    break;
                case BluetoothDevice.BOND_NONE:
                    ToastUtil.toast("取消配对");
                    Log.e(Constant.PRINT_TAG, "取消配对");
                    break;
                default:
                    break;
            }
        }
    }
};

现在蓝牙连接,在注册信息中不光要把蓝牙的权限打开,还要把位置权限打开

Android Bluetooth(蓝牙)实例

空指针异常啊,View对象没找到,然后使用了。看一下,你的layout里有没有配置这个id啊

找到最后的cased by 很明显的空指针异常

这个是我修改的demo,参考一下 https://download.csdn.net/download/xingge20090606/10314867