Как сделать сопражение с устройством Bluethooth

// Поиск устройств Bluethooth

    mBluetoothAdapter.startDiscovery(); 
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    //Finding devices                 
    if (BluetoothDevice.ACTION_FOUND.equals(action)) 
    {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // Add the name and address to an array adapter to show in a ListView
       mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
  }
};

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter);

// Получение списка сопряженных устройств:

    public class PairedDeviceActivity extends AppCompatActivity {
  private ListView listView;
  private ArrayList<String> mDeviceList = new ArrayList<>();

private void getBluetoothPairedDevices(final ArrayList<String> deviceList, final ListView listView){
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        Toast.makeText(getApplicationContext(), "This device not support bluetooth", Toast.LENGTH_LONG).show();
    } else {
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableAdapter, 0);
        }
        Set<BluetoothDevice> all_devices = bluetoothAdapter.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 onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_paired_device);
    listView = findViewById(R.id.listView);
    getBluetoothPairedDevices(mDeviceList,listView);
 }
}

а как теперь при нажатии на устройство сопрячся с ним?


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

Автор решения: Andrew

Клик по элементу списка делается так:

listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
});

в данной функции нас интересует position. Дальше берем данные из массива устройств по данной позиции:

all_devices[position]

Кстати вот у вас заметил, адаптер у вас сетится в цикле, а это мне кажется не очень правильно, лучше чтобы было так:

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));
        }

само подключение происходит следующим образом:

BluetoothDevice device = (BluetoothDevice) parent.getItemAtPosition(position);
myThreadConnectBTdevice = new ThreadConnectBTdevice(device);
myThreadConnectBTdevice.start();

и вот класс который я использую для подключения:

 private class ThreadConnectBTdevice extends Thread {

        private BluetoothSocket bluetoothSocket = null; 
        private final BluetoothDevice bluetoothDevice; 


        @SuppressLint("SetTextI18n")
        private ThreadConnectBTdevice(BluetoothDevice device) 
        {
            bluetoothDevice = device;
            try {
                bluetoothSocket = device.createRfcommSocketToServiceRecord(myUUID);
                textStatus.setText("Device name: " + " " + bluetoothDevice.getName());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


        @Override
        public void run()
        {
            boolean success = false;
            try {
                bluetoothSocket.connect(); // попытка соединится
                success = true;
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    bluetoothSocket.close(); // если ошибка вывод сообщения
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

            if (success) {
              // сообщение при удачном подключении к устройству

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });

                startThreadConnected(bluetoothSocket); 
            } else {
                //fail
            }
        }

        void cancel()
        {
            try {
                bluetoothSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

так же для подключения вам нужен идентификатор устройства:

private UUID myUUID;

и присваиваем ему значение:

String UUID_STRING_WELL_KNOWN_SPP = "00001101-0000-1000-8000-00805F9B34FB";
myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);

Вот есть туториал по данному вопросу. И вот статьи 1, 2.

→ Ссылка