Is there any way to catch the moment when two bluetooth devices have been paired?
Actually I have an application with two ListView
s - one with paired devices and another with newly discovered devices. Each time a user chooses a device from a Newly discovered devices list, an alert dialog box appears asking whether he wants to pair with this device. After clicking YES, a pairDevice function executes and two lists must be updated so the device with which we paired dissapears from the list "Newly discovered devices" and is added to the list "Paired devices".
I could create two lists, write a discovery function, add onClickevent
for the list "Newly Discovered devices" and write pairDevice
function for it but each time I start my application and click on the item from Newly Discovered devices list, a program craches with a message "Unfortunately your application has stopped" but below I've got another dialog window asking if I want to pair with a chosen device (here is a screenshot) which means that the application is still working.
Here is a part of my code where I try to pair devices and update lists:
// New Devices List
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrListNew);
newListView = (ListView) findViewById(R.id.new_lv);
titleNewListView = (TextView)findViewById(R.id.title_new_lv);
// New Devices List View item click
newListView.setClickable(true);
// Newly discovered devices OnClick Event
newListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String info = ((TextView) view).getText().toString();
int address = info.indexOf(":");
final String adr = info.substring(address-2,info.length());
// Pair two devices method
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Pair with a chosen device?");
builder.setPositiveButton("yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr);
pairDevice(device);
// update list with Paired Devices
arrListPaired.add(device);
mPairedDevicesArrayAdapter.notifyDataSetChanged();
// update list with Newly Discovered Devices
arrListNew.remove(device);
mNewDevicesArrayAdapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("No", new OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
And my pairDevice
function:
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks in advance for any suggestions!