I want to listen for incoming messages through bluetooth when pairing totally completed. I can't call listen(can I?) before the pairing is completed and I can't know when it is completed.
I tried a lot of methods to pair between two devices like this one:
private void pairDevice() {
try {
BluetoothDevice device = bluetooth.getRemoteDevice(address);
Log.d("pairDevice()", "Start Pairing...");
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
Log.d("pairDevice()", "Pairing finished.");
} catch (Exception e) {
Log.e("pairDevice()", e.getMessage());
}
}
this one works nice but it opens a popup to accept the pairing and theLog.d("pairDevice()", "Pairing finished.");
is called before the popup dialog is being accepted and I need to do things only when the pairing is totally completed and the devices are now paired. here is my code for listening for messages:
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
textview.setText(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
here is my code for sending the message(score):
private void init() throws IOException {
if (bluetooth != null) {
if (bluetooth.isEnabled()) {
Set<BluetoothDevice> bondedDevices = bluetooth.getBondedDevices();
if (bondedDevices.size() > 0) {
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
write(score);
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
I tried to pair two devices without user permission like in this answer -here- but it also asked for permissions i don't know why .. So actually I don't think I need pairing without permission I just need doing something when popup accepted. is it possible? thanks.