Android studio:发现蓝牙设备名称未找到,正在努力与设备配对

Android studio:发现蓝牙设备名称未找到,正在努力与设备配对,android,bluetooth,pairing,Android,Bluetooth,Pairing,我开发了一个应用程序,它使用一个特定的蓝牙模块(HC-06)与之通信,但首先它需要与之配对,并且它使用以下代码来实现这一点 BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); ListView lView; ArrayList<String> devNameList, devAddressList; private ListAdapter arrayAdapter; private C

我开发了一个应用程序,它使用一个特定的蓝牙模块(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();
}
BluetoothAdapter mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
列表视图lView;
ArrayList devNameList,devAddressList;
专用列表适配器阵列适配器;
私有连接线程mConnectThread;
私有蓝牙套接字mmSocket=null;
私有静态最终UUID MY_UUID=UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
私有最终静态int请求_ID=2;
//为找到的操作创建广播接收器。
专用最终广播接收器mReceiver=新广播接收器(){
公共void onReceive(上下文、意图){
String action=intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(ACTION)){
//Discovery已找到设备。获取Bluetooth设备
//对象及其来自意图的信息。
BluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA\u设备);
字符串devName=device.getName();
String devAddress=device.getAddress();
添加(devAddress);
if(devName==null){
devName=device.getAddress();
}
添加(devName);
lView.setAdapter(arrayAdapter);
}
}
};
私有类ConnectThread扩展线程{
ConnectThread(蓝牙设备){
BluetoothSocket tmp=null;
试一试{
//获取BluetoothSocket以连接给定的BluetoothDevice。
//MY_UUID是应用程序的UUID字符串,也用于服务器代码中。
tmp=device.createrFComSocketToServiceRecord(我的UUID);
}捕获(IOE异常){
Toast.makeText(getBaseContext(),“错误:套接字的create()方法失败”,Toast.LENGTH\u SHORT.show();
}
mmSocket=tmp;
}
公开募捐{
试一试{
//通过套接字连接到远程设备。此调用将被阻止
//直到它成功或抛出异常。
mmSocket.connect();
}捕获(IOException-connectException){
//无法连接;请关闭套接字并返回。
试一试{
mmSocket.close();
}捕获(IOException关闭异常){
Toast.makeText(getBaseContext(),“错误:无法关闭客户端套接字”,
吐司。长度(短)。show();
}
返回;
}
//连接尝试成功。请执行与关联的工作
//连接在单独的线程中。
manageMyConnectedSocket();
}
//关闭客户端套接字并使线程完成。
作废取消(){
试一试{
mmSocket.close();
}捕获(IOE异常){
Toast.makeText(getBaseContext(),“错误:无法关闭客户端套接字”,
吐司。长度(短)。show();
}
}
}
@凌驾
创建时受保护的void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u add\u new\u device);
请求权限();
lView=findviewbyd(R.id.discList);
devNameList=newarraylist();
DevaAddressList=newArrayList();
arrayAdapter=新的arrayAdapter(这是android.R.layout.simple_list_item_1,devNameList);
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
//在发现设备时注册广播。
IntentFilter筛选器=新的IntentFilter(BluetoothDevice.ACTION\u已找到);
registerReceiver(mrReceiver,过滤器);
mBluetoothAdapter.startDiscovery();
lView.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
字符串devName=devNameList.get(位置);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.KITKAT){
if((Objects.equals(devName,“HC-06”))| |(Objects.equals(devName,“00:21:13:00:97:6A”)){
Toast.makeText(AddNewDevice.this,“请稍候…”,Toast.LENGTH_SHORT.show();
mBluetoothAdapter.cancelDiscovery();
字符串地址=devAddressList.get(位置);
BluetoothDevice=mBluetoothAdapter.getRemoteDevice(地址);
mConnectThread=新的连接线程(设备);
mConnectThread.run();
}
否则{
Toast.makeText(AddNewDevice.this,“请连接到HC-06设备”,Toast.LENGTH_SHORT.show();
}
}
否则{
如果(“HC-06”。等于(devName)|“00:21:13:00:97:6A”。等于(devName)){
Toast.makeText(AddNewDevice.this,“请稍候…”,Toast.LENGTH_SHORT.show();
mBluetoothAdapter.cancelDiscovery();
字符串地址=devAddressList.get(位置);
BluetoothDevice=mBluetoothAdapter.getRemoteDevice(地址);
mConnectThread=新的连接线程(设备);
mConnectThread.run();
}
否则{
Toast.makeText(AddNewDevice.this,“请连接到HC-06设备”,Toast.LENGTH_SHORT.show();
}
}
}
});
}
私有void requestPermissions(){
int androidVersion=Build.VERSION.SDK\u int;
如果(androidVersion>=23){
ActivityCompat.requestPermissions(此,
新字符串[]{Manifest.permission.ACCESS\u FINE\u位置,
Manifest.permission.ACCESS\u位置,
},请求ID);
}
}
@凌驾
受保护的空onDestroy(){
super.ondestory();
注销
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
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);
        }
    }