2

我开发了一个应用程序,它使用特定的蓝牙模块(HC-06)与之通信,但首先它需要与之配对,它使用以下代码进行配对......

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ListView lView;
ArrayList<String> devNameList, devAddressList;

private ListAdapter arrayAdapter;
private ConnectThread mConnectThread;
private BluetoothSocket mmSocket = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private final static int REQUEST_ID = 2;

// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = 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 devName = device.getName();
            String devAddress = device.getAddress();

            devAddressList.add(devAddress);

            if (devName == null){
                devName = device.getAddress();
            }

            devNameList.add(devName);

            lView.setAdapter(arrayAdapter);
        }
    }
};

private class ConnectThread extends Thread {
    ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;

        try {
            // Get a BluetoothSocket to connect with the given BluetoothDevice.
            // MY_UUID is the app's UUID string, also used in the server code.
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "ERROR: Socket's create() method failed", Toast.LENGTH_SHORT).show();
        }
        mmSocket = tmp;
    }

    public void run() {
        try {
            // Connect to the remote device through the socket. This call blocks
            // until it succeeds or throws an exception.
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and return.
            try {
                mmSocket.close();
            } catch (IOException closeException) {
                Toast.makeText(getBaseContext(), "ERROR: Could not close the client socket",
                        Toast.LENGTH_SHORT).show();
            }
            return;
        }
        // The connection attempt succeeded. Perform work associated with
        // the connection in a separate thread.
        manageMyConnectedSocket();
    }

    // Closes the client socket and causes the thread to finish.
    void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "ERROR: Could not close the client socket",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

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

    requestPermissions();

    lView = findViewById(R.id.discList);

    devNameList = new ArrayList<>();
    devAddressList = new ArrayList<>();
    arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, devNameList);

    if (mBluetoothAdapter.isDiscovering()){
        mBluetoothAdapter.cancelDiscovery();
    }
    // Register for broadcasts when a device is discovered.
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
    mBluetoothAdapter.startDiscovery();

    lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String devName = devNameList.get(position);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if((Objects.equals(devName, "HC-06"))|| (Objects.equals(devName, "00:21:13:00:97:6A"))){
                    Toast.makeText(AddNewDevice.this, "Please wait...", Toast.LENGTH_SHORT).show();

                    mBluetoothAdapter.cancelDiscovery();

                    String address = devAddressList.get(position);
                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                    mConnectThread = new ConnectThread(device);
                    mConnectThread.run();
                }
                else{
                    Toast.makeText(AddNewDevice.this, "Please connect to an HC-06 device.", Toast.LENGTH_SHORT).show();
                }
            }
            else {
                if("HC-06".equals(devName) || "00:21:13:00:97:6A".equals(devName)){
                Toast.makeText(AddNewDevice.this, "Please wait...", Toast.LENGTH_SHORT).show();

                mBluetoothAdapter.cancelDiscovery();

                String address = devAddressList.get(position);
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                mConnectThread = new ConnectThread(device);
                mConnectThread.run();
                }
                else{
                    Toast.makeText(AddNewDevice.this, "Please connect to an HC-06 device.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
}

private void requestPermissions(){
    int androidVersion = Build.VERSION.SDK_INT;
    if (androidVersion >= 23){
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                }, REQUEST_ID);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mReceiver);
    mBluetoothAdapter.cancelDiscovery();
}

private void manageMyConnectedSocket() {
    mConnectThread.cancel();
    finish();
}

该代码在运行 API 17 (Android 4.2.2) 的设备上运行良好,但在 API 23 (android 6.0) 设备上它有点小故障:

首先,它有时会找到设备名称,有时却找不到(这就是为什么我在第 50 行和第 51 行 [如果您复制了代码]、第 23 行和第 24 行没有导入标头)

其次,我注意到当它没有获得设备名称并且我尝试连接时,它很难配对/连接到设备(在我的蓝牙设置中它只是永远显示“配对...”)但是当它确实获得它正确配对的设备名称。

谁能帮我解决这个故障?

4

1 回答 1

1

几天前我回答了这个问题。链接如下。您在使用较新版本的 Android 时遇到的问题是,它需要粗略和精细位置权限才能使用较新版本的 android 进行发现。包含这些权限后,查找设备然后与它们配对应该可以工作。

链接无法发现可用的蓝牙设备

我的帖子来自上面的链接:

尝试同时添加粗略位置权限。我的应用程序有 Fine 和 Coarse,它适用于 API 19 (Kit Kat)、API 21 (Lollipop)、API 23 (Marshmallow) 和 API 24 (Nougat)。

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

还要确保在应用程序中到达此位置之前请求许可。因此,在 onCreate 添加以下方法以确保在更高版本的 Android 上请求您的权限。我知道我还需要添加此代码才能使其正常工作。您可以将自己定义的 int 用于 REQUEST_ID。当您为更高版本的android加载应用程序时,它将向用户弹出提示。

private int androidVersion; //define at top of code as a variable

private void requestPermissions(){
androidVersion = Build.VERSION.SDK_INT;
        if (androidVersion >= 23){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION,                                
                    }, REQUEST_ID);
        }
    }
于 2017-12-13T00:47:39.747 回答