Проблемы с отображение списка Bluethooth устройств и их сопряжением

Есть такой код, проблема возникает с блютуз адаптером. Оно ищет то сопряженные устройства то новые устройства по очереди. Так же может дублировать устройства в списке, хотя при поиске новых устройство список очищается перед этим. Далее как сделать чтобы если подключаться к новому устройству оно запрашивало сопряжение и проходило его. Так как если устройство сопряженное, то оно к нему подключается, а если нет то просто не реагирует на клик.

public class MainActivity extends AppCompatActivity {

    private static final int REQ_CODE_VOICE = 1000;
    private static final int REQ_CODE_BT = 1001;
    private static final int REQUEST_COARSE_LOCATION = 1002;
    private Button microphoneButton;
    private ToggleButton powerButton;
    private ToggleButton bluethoothButton;
    private EditText runStringEdit;
    private BluetoothAdapter mBluetoothAdapter;
    private ProgressDialog mProgressDialog;
    private ArrayAdapter mArrayAdapter;
    private RecyclerView listDevices;
    private MyRecycleViewAdapter mDeviceListAdapter;
    private Dialog devicesDialog;
    private TextView txtDeviceConnectedName;

    ThreadConnectBTdevice myThreadConnectBTdevice;
    private ArrayList<BluetoothDevice> mDevices = new ArrayList<>();
    private String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.RECORD_AUDIO,
    };


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

        microphoneButton = findViewById(R.id.microphone_button);
        powerButton = findViewById(R.id.power_button);
        bluethoothButton = findViewById(R.id.bluetooth_button);
        runStringEdit = findViewById(R.id.run_string_edit);
        txtDeviceConnectedName = findViewById(R.id.txtDeviceConnectedName);

        mBluetoothAdapter = mBluetoothAdapter.getDefaultAdapter();

//     Обработчик OnClick
        View.OnClickListener OnClick = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.microphone_button:
                        OnClickMicrophone();
                        break;
                    case R.id.power_button:
                        break;
                    case R.id.bluetooth_button:
                        if (bluethoothButton.isChecked())
                            enableBluetooth();
                        else
                            disableBluetooth();
                        break;
                }
            }
        };

        microphoneButton.setOnClickListener(OnClick);
        powerButton.setOnClickListener(OnClick);
        bluethoothButton.setOnClickListener(OnClick);

        checkLocationPermission();
    }


    @Override
    protected void onResume() {
        super.onResume();
        stateBluethooth();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mRecevier);
        super.onDestroy();
    }

    // Топ Меню
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.topmenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            findNewDevices();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_COARSE_LOCATION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                }
                break;
            }
        }
    }

    private void checkLocationPermission() {
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i])
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{permissions[i]}, REQUEST_COARSE_LOCATION);
            }
        }
    }


    public void OnClickMicrophone() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        startActivityForResult(intent, REQ_CODE_VOICE);
    }


    //          Если блютуз не поддерживаеться
    private void noSupportedBluetooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.noSupportedBluethooth, Toast.LENGTH_LONG).show();
        }
    }

    //           Включаем блютуз
    private void enableBluetooth() {
        if (!mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQ_CODE_BT);
        }
    }

    //          Проверяем состояние блютуз
    private void stateBluethooth() {
        bluethoothButton.setChecked(mBluetoothAdapter.isEnabled());
    }


    //          Выключаем блютуз
    private void disableBluetooth() {
        if (myThreadConnectBTdevice != null) {
            myThreadConnectBTdevice.cancel();
        }
        if (txtDeviceConnectedName != null)
            txtDeviceConnectedName.setText("Устройство: не подключено");


        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
        }
    }

    private void findNewDevices() {
        if (!mBluetoothAdapter.isEnabled()) {
            enableBluetooth();
            return;
        }

        mBluetoothAdapter.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_UUID);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mRecevier, filter);
    }


    private void showListDevices() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Найденые устройства");

        View view = getLayoutInflater().inflate(R.layout.list_devices_view, null);
        listDevices = view.findViewById(R.id.list_devices);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        listDevices.setLayoutManager(layoutManager);

        mDeviceListAdapter = new MyRecycleViewAdapter(mDevices, new MyRecycleViewAdapter.RVClickListener() {
            @Override
            public void itemOnClick(BluetoothDevice device) {
                connect(device);
            }
        });

        listDevices.setAdapter(mDeviceListAdapter);

        builder.setView(view);
        builder.setNegativeButton("OK", null);
        builder.create();
        devicesDialog = builder.show();
    }

    private void connect(BluetoothDevice device) {
        if (myThreadConnectBTdevice != null) {
            myThreadConnectBTdevice.cancel();
        }
        myThreadConnectBTdevice = new ThreadConnectBTdevice(device);
        myThreadConnectBTdevice.start();
    }

    //Поиск сопраженные девайсов
    private void findParedDevices(final ArrayList<String> deviceList, final ListView listView) {
        Set<BluetoothDevice> all_devices = mBluetoothAdapter.getBondedDevices();
        if (all_devices.size() > 0) {
            for (BluetoothDevice currentDevice : all_devices) {
                deviceList.add("Device Name: " + currentDevice.getName() + "\nDevice Address: " + currentDevice.getAddress());
//                listView.setAdapter(new ArrayAdapter<>(getApplication(),
//                        android.R.layout.simple_list_item_1, deviceList));
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQ_CODE_BT:
//                    searchDevices();
                    break;
                case REQ_CODE_VOICE:
                    if (data != null) {
                        ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                        runStringEdit.setText(text.get(0));
                    }
                    break;
            }
        } else if (requestCode == RESULT_CANCELED) {
            switch (requestCode) {
                case REQ_CODE_BT:
                    bluethoothButton.setChecked(false);
                    break;
            }
        }
    }


    private BroadcastReceiver mRecevier = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                mDevices.clear();
                mProgressDialog = ProgressDialog.show(MainActivity.this, "Поиск устройств", " Пожалуйста подождите...");
            }

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDevices.add(device);
            }

            // поиск устройств завершен
            if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                mProgressDialog.dismiss();
                showListDevices();
            }
        }
    };

    private class ThreadConnectBTdevice extends Thread {
        private BluetoothSocket bluetoothSocket = null;
        private final BluetoothDevice bluetoothDevice;

        @SuppressLint("SetTextI18n")
        private ThreadConnectBTdevice(BluetoothDevice device) {
            bluetoothDevice = device;
//                 TODO Auto-generated catch block
        }

        @Override
        public void run() {
            boolean success = false;
            try {
                ParcelUuid[] uuids = bluetoothDevice.getUuids();
                if (uuids != null) {
                    for (ParcelUuid uuid : uuids) {
                        String UUID_STRING_WELL_KNOWN_SPP = uuid.getUuid().toString();
                        UUID myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);
                        bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(myUUID);
                        try {
                            bluetoothSocket.connect(); // попытка соединится
                            success = true;
                            break;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }


            if (success) {
                // сообщение при удачном подключении к устройству
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (devicesDialog != null) {
                            devicesDialog.dismiss();
                        }
                        if (txtDeviceConnectedName != null) {
                            txtDeviceConnectedName.setText("Устройство: '" + bluetoothDevice.getName() + "' подключено");
                        }
                    }
                });
            } else {
            }
        }

        void cancel() {
            try {
                if (bluetoothSocket != null)
                    bluetoothSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

Ответы (0 шт):