Как предотвратить несколько ящиков AlertDialog - PullRequest
0 голосов
/ 25 марта 2020

Я пытаюсь показать все обнаруженные устройства Bluetooth в AlertDialog, используя setItems(). Проблема в том, что каждый раз, когда обнаруживается новое устройство, появляется новое AlertDialog. Я попытался отменить это, проверив, равно ли dialog.isShowing() истине, но всегда возвращает ложь.

Чего мне не хватает?

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    ArrayList<String> addressDevice = new ArrayList<String>();
    ArrayList<String> nameDevice = new ArrayList<String>();
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            // Discovery starts, we can show progress dialog or perform other tasks
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            // Discovery finished, dismiss progress dialog
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Device found
            BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.w("BT", "Found Device" + device.getAddress());
            nameDevice.add(device.getName());
            addressDevice.add(device.getAddress());
            Log.w("BT", Arrays.toString(addressDevice.toArray()));
            //Log.w("BT", "Discovery stopped");
            createAlertDialog(nameDevice, addressDevice);
        }
    }
};

void createAlertDialog(ArrayList listDevices, ArrayList addressDevices) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Found devices");
    // alertDialog.setMessage("These are the found devices.");
    CharSequence[] cs = (CharSequence[]) listDevices.toArray(new CharSequence[listDevices.size()]);
    builder.setItems(cs, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
                String selectedDeviceAddress = addressDevices.get(which).toString();
                Log.w("BT", "selected device address is" + addressDevices.get(which).toString());
                bluetoothAdapter.cancelDiscovery();
                dialog.dismiss();
                connectToDevice(selectedDeviceAddress);
        }
    });
    AlertDialog dialog = builder.create();
    Log.w("BT", String.valueOf(dialog.isShowing()));
    if(dialog.isShowing()){
        dialog.dismiss();
    }
    dialog.show();
}
...