I have a class which used to pair and connect to a Bluetooth device. I am using Android 6.0 to implement it. The application has two buttons which are for pair and connection function. It worked well for pair function. However, I cannot implement the connection function. I looked at some example of Bluetooth connection but they are not working when I used in this class. Please look at my class and give me some direction to implement it? Thanks all
public class DeviceListActivity extends Activity {
private ListView mListView;
private DeviceListAdapter mAdapter;
private ArrayList<BluetoothDevice> mDeviceList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(mDeviceList);
mAdapter.setPairListener(new DeviceListAdapter.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
showToast("Pairing...");
pairDevice(device);
}
}
});
mAdapter.setConnectListener(new DeviceListAdapter.OnConnectButtonClickListener() {
#Override
public void onConnectButtonClick(int position) {
//Connect bluetooth
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void connectDevice(BluetoothDevice device) {
// Connect bluetooth
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Paired");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Unpaired");
}
mAdapter.notifyDataSetChanged();
}
}
};
}
Connecting as a client is simple. Your first obtain the RFCOMM socket from the desired BluetoothDevice by calling createRfcommSocketToServiceRecord(), passing in a UUID, a 128-bit value that you create. The UUID is similar to a port number
if you hold the Bluetooth device from the paired list, you can just use this class to connect to it,
public class ConnectThread extends Thread{
private BluetoothSocket bTSocket;
public boolean connect(BluetoothDevice bTDevice, UUID mUUID) {
BluetoothSocket temp = null;
try {
temp = bTDevice.createRfcommSocketToServiceRecord(mUUID);
} catch (IOException e) {
Log.d("CONNECTTHREAD","Could not create RFCOMM socket:" + e.toString());
return false;
}
try {
bTSocket.connect();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not connect: " + e.toString());
try {
bTSocket.close();
} catch(IOException close) {
Log.d("CONNECTTHREAD", "Could not close connection:" + e.toString());
return false;
}
}
return true;
}
public boolean cancel() {
try {
bTSocket.close();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not close connection:" + e.toString());
return false;
}
return true;
}
}
i would suggest using this tutorial as a startup point to learn from and know more on how Bluetooth in android works.
http://code.tutsplus.com/tutorials/create-a-bluetooth-scanner-with-androids-bluetooth-api--cms-24084
Related
I am trying to connect to another Bluetooth through programmatically in android but continuously I am getting this error. anyone, please help me to connect Bluetooth. is there anything wrong with my code. i am working with bluetooth from last 2 weeks but unable to connect to the bluetooth.
is there working source code availble in github it may be helpful for me
Error-> BluetoothAdapter: getBluetoothService() called withBluetoothManagerCallback
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice mBluetoothDevice;
ListView paired_lv;
Button paired_btn, listen, sendData;
TextView deviceTxt;
ClientSocket socket;
ConnectedThread connectedThread;
private static final UUID MY_UUID_SECURE =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paired_btn = findViewById(R.id.paired_devices);
paired_lv = findViewById(R.id.paired_lv);
deviceTxt = findViewById(R.id.device_name);
listen = findViewById(R.id.listen);
sendData = findViewById(R.id.send_data);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null){
toast("Your device doesn't support bluetooth adapter");
}else if (!mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.enable();
}
paired_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pairedDevices();
}
});
paired_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
BluetoothDevice device = (BluetoothDevice) adapterView.getItemAtPosition(i);
toast("clicket"+device.getName() );
socket = new ClientSocket(device);
socket.start();
}
});
listen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// AcceptThread acceptThread = new AcceptThread();
//acceptThread.start();
if (socket != null){
socket.cancel();
}
}
});
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mes = "bhanu";
Log.d("BT","Send button clicked");
connectedThread.write("bhanu");
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(mReceiver,filter);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
Log.d("BT","device connected");
toast("device connected");
}else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
toast("device disconnected");
}
}
};
public void toast(String message){
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
public void pairedDevices(){
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
ArrayList<BluetoothDevice> arrayList = new ArrayList<>();
if (devices.size()<0){
toast("no paired devices found");
}else {
for (BluetoothDevice device:devices){
toast(device.getName());
arrayList.add(device);
ArrayAdapter<BluetoothDevice> adapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList);
paired_lv.setAdapter(adapter);
}
}
}
private class ClientSocket extends Thread{
private final BluetoothDevice mDevice;
private final BluetoothSocket mSocket;
public ClientSocket(BluetoothDevice device,Boolean isSecure) {
mDevice = device;
BluetoothSocket tmp = null;
boolean secure = isSecure;
try {
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
} catch (IOException e) {
e.printStackTrace();
}
mSocket = tmp;
}
#Override
public void run() {
mBluetoothAdapter.cancelDiscovery();
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d("BT","bonded");
}
if (BluetoothDevice.DEVICE_TYPE_LE == mDevice.getType()){
try {
Log.d("BT","Connecting BT");
Log.d("BT","socket info"+ mSocket);
mSocket.connect();
Log.d("BT","Connected BT");
} catch (IOException e) {
cancel();
e.printStackTrace();
}
}
if (mSocket != null){
connectedThread = new ConnectedThread(mSocket);
}
}
public void cancel(){
if (mSocket.isConnected()){
try {
mSocket.close();
Log.d("BT","socket was closed");
} catch (IOException e) {
e.printStackTrace();
}
}else {
Log.d("BT","device not connected to the any other device");
}
}
}
private class AcceptThread extends Thread{
private final BluetoothServerSocket mServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("Bhanu",MY_UUID_INSECURE);
} catch (IOException e) {
e.printStackTrace();
}
mServerSocket = tmp;
}
#Override
public void run() {
BluetoothSocket socket = null;
while (true){
try {
//Toast.makeText(getApplicationContext(),"ready to accept",Toast.LENGTH_SHORT).show();
Log.d("BT","ready to accept socket");
socket = mServerSocket.accept();
Log.d("BT","socket accepted");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}
You need a BluetoothManager
BluetoothManager mBluetoothManager;
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(this);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
}
While I am trying to connect to the Bluetooth device in a listview, I am getting error
in listview I am passing Bluetooth device to the second class it extends thread. Error:
getBluetoothService() called with no BluetoothManagerCallback,
ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget
Button PairedBT, ScanBt;
ListView pairedListView;
public BluetoothAdapter mBluetoothAdapter;
ArrayAdapter<String> mAdapter;
ArrayList<String> mArrayList = new ArrayList<String>();
BluetoothDevice[] btArray = new BluetoothDevice[30];
//ArrayList<BluetoothDevice> connectDevice = new ArrayList<BluetoothDevice>();
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PairedBT = findViewById(R.id.pairedBt);
pairedListView = findViewById(R.id.list_view_paired);
ScanBt = findViewById(R.id.scanBt);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
PairedBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
String[] names = new String[devices.size()];
int index = 0;
if (devices.size() > 0) {
for (BluetoothDevice device : devices) {
names[index] = device.getName();
index++;
}
//mAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,names);
// pairedListView.setAdapter(mAdapter);
}
}
});
ScanBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBluetoothAdapter.startDiscovery();
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, mArrayList);
pairedListView.setAdapter(mAdapter);
pairedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//pairDevice(btArray[i]);
BluetoothDevice device = btArray[i];
// BluetoothDevice device = (BluetoothDevice) pairedListView.getAdapter().getItem(i);
ClientSocket clientSocket = new ClientSocket(device);
Toast.makeText(getApplicationContext(), "at" + btArray[i], Toast.LENGTH_SHORT).show();
//mBluetoothAdapter.cancelDiscovery();
clientSocket.start();
//sendBT();
}
});
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String acton = intent.getAction();
toast("onReceive method");
int i = 0;
if (BluetoothDevice.ACTION_FOUND.equals(acton)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
btArray[i] = device;
i++;
//connectDevice.add(device);
mArrayList.add(device.getName());
toast("found");
mAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
#Override
protected void onPause() {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
super.onPause();
}
public void toast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
public void sendBT() {
OutputStream out = null;
String sample = "Welcome to qualtech";
// out.write(sample.getBytes());
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private void unPairDevice(BluetoothDevice device) {
Method method = null;
try {
method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object) null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private class ClientSocket extends Thread {
private BluetoothDevice mDevice;
private BluetoothSocket mSocket;
private boolean mSecure;
// private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public ClientSocket(BluetoothDevice device) {
mDevice = device;
BluetoothSocket tmp = null;
mBluetoothAdapter.cancelDiscovery();
try {
Log.d("BT", "BT creating RfcommSocketService");
tmp = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
Log.d("BT", "BT Connecting");
mSocket.connect();
Log.d("BT", "Connected succesufully");
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try moving your intent filter code (6 lines of code) above mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
I'm developing an Android app that is a kind of a remote control (that works via bluetooth) for one Arduino device. I've already could pair my phone with remote Bluetooth. Also it seems that I could establish connection which I've checked with an ACTION_ACL_CONNECTED state like this:
private final BroadcastReceiver connectedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
showToast("Conneeeeeeeeeeeeected");
}
}
};
The problem is when I press a button on my app to send some data to the remote Bluetooth, nothing happens (a LED must change its state from OFF to ON). Could you please check what's wrong, maybe it's something with my ConnectThread? Here is my code:
public class MainActivity extends AppCompatActivity {
private final static UUID MY_UUID = UUID.fromString("ecff8f1a-ac66-11e6-80f5-76304dec7eb7");
BluetoothSocket mmSocket;
Button whiteBtn; // after clicking this button, data from my phone are send to remote bluetooth
whiteBtn = (Button) findViewById(R.id.white_btn);
whiteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
whiteBtnOn();
}
});
#Override
protected void onCreate(Bundle savedInstanceState) {
// Get Bluetooth Adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
showToast("Bluetooth is not supported on this device");
}
// Enable Bluetooth
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListPaired);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
// Find out which devices have been already paired
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
showToast("Paired devices have been found");
// Loop through the paired devices
for (BluetoothDevice device : pairedDevices) {
arrListPaired.add(device.getName() + '\n' + device.getAddress());
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListPaired);
}
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
}
// Click event for items from paired devices list (Possible actions: “Connect”, which establishes connection between my phone and remote Bluetooth, “Unpair”, “Cancel”)
pairedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
final String info = ((TextView) view).getText().toString();
int address = info.indexOf(":");
final String adr = info.substring(address - 2, info.length());
final int positionToRemove = position;
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("What should we do?");
//builder.setMessage("Unpair this device?");
builder.setPositiveButton("Unpair", new OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr);
// UNPAIR DEVICES
unpair(device);
arrListPaired.remove(positionToRemove);
mPairedDevicesArrayAdapter.notifyDataSetChanged();
// END UNPAIR DEVICES
}
});
builder.setNeutralButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
// Establish Connection between devices
builder.setNegativeButton("Connect", new OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
showToast("Establish connection");
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr);
ConnectThread ct = new ConnectThread(device);
ct.start();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
registerReceiver(connectedReceiver, filter);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
#Override
protected void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(receiver, filter);
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpair(BluetoothDevice device) {
showToast("Unpaired button is clicked");
try {
if(mmSocket!=null) {mmSocket.close();}
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Connecting threat
private class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {}
mmSocket = tmp;
}
public void run () {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) {}
return;
}
//manageConnectedSocket(mmSocket);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {}
}
}
// Managing a connection
// Broadcast receiver for connected device
private final BroadcastReceiver connectedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
showToast("Conneeeeeeeeeeeeected");
}
}
};
// Send data after clicking on a button
private void whiteBtnOn() {
if (mmSocket != null) {
showToast("White btn is clicked");
try {
mmSocket.getOutputStream().write("TO".toString().getBytes());
}
catch (IOException e) {}
}
}
}
}
Thanks in advance for your suggestions!
Try use UUID for Bluetooth SPP:
private final static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
instead of:
private final static UUID MY_UUID = UUID.fromString("ecff8f1a-ac66-11e6-80f5-76304dec7eb7");
My code can scan and pair bluetooth speakers. However, in order to stream audio to the paired device, I have to pair via device settings or it won't work. How do I do this via my app?
public class DeviceListActivity extends Activity {
private ListView mListView;
private DeviceListAdapter mAdapter;
private ArrayList<BluetoothDevice> mDeviceList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(mDeviceList);
mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
showToast("Connecting..");
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Connected! now you can stream");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Disconnected");
}
mAdapter.notifyDataSetChanged();
}
}
};
}
I am trying to make a pairing by code and it works only for normal devices. If I use a bluetooth scanner it pairs with it but the device doesn't work till I go to android settings and select the Input Device checkbox. How can I do this by code?
Thank you.
Here is my pairing code:
public static BluetoothSocket createL2CAPBluetoothSocket(String address, int psm){
return createBluetoothSocket(TYPE_L2CAP, -1, false,false, address, psm);
}
// method for creating a bluetooth client socket
private static BluetoothSocket createBluetoothSocket(
int type, int fd, boolean auth, boolean encrypt, String address, int port){
try {
Constructor<BluetoothSocket> constructor = BluetoothSocket.class.getDeclaredConstructor(
int.class, int.class,boolean.class,boolean.class,String.class, int.class);
constructor.setAccessible(true);
BluetoothSocket clientSocket = (BluetoothSocket)
constructor.newInstance(type,fd,auth,encrypt,address,port);
return clientSocket;
}catch (Exception e) { return null; }
}
private void doPair(final BluetoothDevice device, final int deviceTag) {
try {
Method method = device.getClass().getMethod("createBond",
(Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e(LOG_TAG, "Cannot pair device", e);
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(
BluetoothDevice.EXTRA_BOND_STATE,
BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(
BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE,
BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED
&& prevState == BluetoothDevice.BOND_BONDING) {
Log.d(LOG_TAG, "Paired with new device");
if (listener != null) {
listener.onBluetoothPairedDeviceChange(bluetoothAdapter
.getBondedDevices().iterator().next()
.getName(), deviceTag);
}
context.unregisterReceiver(this);
} else if (state == BluetoothDevice.BOND_NONE
&& prevState == BluetoothDevice.BOND_BONDING) {
Log.d(LOG_TAG, "Cannot pair with new device");
if (listener != null) {
listener.onBluetoothStatusChange(BluetoothHelper.IDLE_STATUS);
}
context.unregisterReceiver(this);
}
}
}
};
IntentFilter intent = new IntentFilter(
BluetoothDevice.ACTION_BOND_STATE_CHANGED);
context.registerReceiver(mReceiver, intent);
}
First,if your target version after API 19 , you can use BluetoothDevice.createBond() to pair the device directly without use reflection.
Following methods only work on devices before android 6.0!(After 6.0, system will do some caller check to avoid outer app to call these methods)
BluetoothAdapter.getDefaultAdapter().getProfileProxy(MainActivity.this, new BluetoothProfile.ServiceListener() {
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Class<?> clazz = null;
try {
clazz = Class.forName("android.bluetooth.BluetoothInputDevice");
Object obj = clazz.cast(proxy);
Method connectMethod = clazz.getDeclaredMethod("connect",BluetoothDevice.class);
boolean resultCode = (boolean) connectMethod.invoke(obj,device);
Method setPriority = clazz.getDeclaredMethod("setPriority",BluetoothDevice.class,int.class);
setPriority.invoke(obj,device,1000);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(int profile) {
Log.d("wtf","onservice disconnected "+profile);
}
},INPUT_DEVICE);
final int INPUT_DEVICE = 4; // this is hidden memeber in BluetoothDevice