Connection between android device and bluetooth headsets programatically - android

How can i make an app in android that can provide connection between the android device and the bluetooth speakers.

How to pair:
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
How to Unpair:
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
The receiver to catch the pairing process:
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");
}
}
}
};
Register receiver:
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);

Related

Capture bluetooth upon paired state

I have a listViewwhich will display a list of paired bluetooth devices. I wanna capture the state inorder to update the paired listView whenever a new request to pair with my device gets accepted.
So far I have tried listening to BluetoothDevice.ACTION_ACL_CONNECTED but to no avail.
protected void onCreate(Bundle savedInstanceState) {
...
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
this.registerReceiver(mReceiver, filter1);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
getPairedDevices(); // get paired devices and update listView
}
}
First, to scan pair and unpair device, you can you this code
public void scanDevices(){
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
activity.registerReceiver(mReceiverScan, filter);
bluetoothAdapter.startDiscovery();
}
public void pair(BluetoothDevice device){
activity.registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
devicePair=device;
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
if(discoveryCallback!=null)
discoveryCallback.onError(e.getMessage());
}
}
public void unpair(BluetoothDevice device) {
devicePair=device;
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
if(discoveryCallback!=null)
discoveryCallback.onError(e.getMessage());
}
}
private BroadcastReceiver mReceiverScan = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_OFF) {
if (discoveryCallback != null)
discoveryCallback.onError("Bluetooth turned off");
}
break;
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
context.unregisterReceiver(mReceiverScan);
if (discoveryCallback != null)
discoveryCallback.onFinish();
break;
case BluetoothDevice.ACTION_FOUND:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (discoveryCallback != null)
discoveryCallback.onDevice(device);
break;
}
}
};
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) {
if(discoveryCallback!=null)
discoveryCallback.onPair(devicePair);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
if(discoveryCallback!=null)
discoveryCallback.onUnpair(devicePair);
}
}
}
};
Finally, you can add these device to a list as
public List<BluetoothDevice> getPairedDevices(){
List<BluetoothDevice> devices = new ArrayList<>();
for (BluetoothDevice blueDevice : bluetoothAdapter.getBondedDevices()) {
devices.add(blueDevice);
}
return devices;
}
Don't forget to add permission in AndroidManifet.xml file
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
This is a good library that I used is
https://github.com/omaflak/Bluetooth-Library
And this is a sample app to use the above lib.
https://github.com/omaflak/Bluetooth-Android

How to connect to a bluetooth device when they are paired?

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

How to connect to a paired bluetooth device?

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

Android bluetooth connection throwing read failed, socket might closed or timeout, read ret android

I am trying to communicate from android to a microprocessor controlled device, which uses HC-05, I have tried every possible solution, but btSocket.connect() is throwing
read failed, socket might closed or timeout, read ret android
Relevant code snippet is provided below:-
/**
* Sends the data Over BlueTooth
* #param data
* bytes which is to be send to the bibox.
*
* */
private void sendDataToBlueTooth(byte[] data){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String mMacChecking = pref.getString("BL", "bl");
if (!mMacChecking.equals("bl")) {
// Intent in = new Intent(getApplicationContext(), DataSendReceive.class);
// in.putExtra("isBtRemoteData", true);
// in.putExtra("bData", data);
// startActivity(in);
final SharedPreferences pre = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
this.mDeviceMACAddress = pre.getString("BL", "");
this.mSendArray = data;
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
Toast.makeText(this, R.string.no_bt_device, Toast.LENGTH_LONG).show();
this.finish();
return;
}
this.connectTOdevice();
this.mHandler = new Handler() {
#SuppressLint("ShowToast")
#Override
public void handleMessage(final android.os.Message msg) {
if (msg.what == 1) {
mConnectStatus = true;
for (int i = 0; i < mSendArray.length; i++) {
write(mSendArray[i]);
}
String str = Arrays.toString(mSendArray);
Log.d("", str);
//Added an alert dialog to show the data..
// To activate the alert, put the below 3 lines inside the on click of the OK button...
onBackPressed();
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
} else if (msg.what == 2) {
// Set button to display current status
// connectStat = true;
final byte[] readBuf = (byte[]) msg.obj;
System.out.println("InHandler - ");
String receivedString = "";
for (final byte b : readBuf) {
// `byte` to `Byte`
final int temp = b;
final String tempString = String.valueOf(temp);
receivedString = receivedString.concat("," + tempString);
}
Log.d("received string", receivedString);
for (final byte element : readBuf) {
System.out.print(element + ",");
}
// System.out.println("" + readBuf);
} else if (mBluetoothAdapter.isEnabled()) {
final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
// Connection failed
mFailToast.show();
/* Intent scan = new Intent(getApplicationContext(), BluetoothDeviceDiscover.class); */
finish();
// startActivity(scan);
}
}
};
mFailToast = Toast.makeText(this, "Failed to connect please on " + this.mDeviceMACAddress + " or scan for new device", Toast.LENGTH_SHORT);
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
Toast.makeText(this, R.string.no_bt_device, Toast.LENGTH_LONG).show();
this.finish();
return;
}
this.connectTOdevice();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (this.mBtSocket != null) {
this.mBtSocket.close();
}
} catch (final IOException e2) {}
}
public void write(final byte arr2) {
if (this.mConnectStatus == true) if (this.mOutStream != null) {
try {
this.mOutStream.write(arr2);
} catch (final IOException e) {
showToast(getString(R.string.dataNotSendMessage), false);
}
} else {
showToast(getString(R.string.switchOnBlueToothDevice), false);
}
}
public void connectTOdevice() {
this.mConnectThread = new ConnectThread(this.mDeviceMACAddress);
this.mConnectThread.start();
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
boolean isUnpairToastToBeDisplayed = true;
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String DEVICE_PIN = getString(R.string.device_pin);
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals("android.bluetooth.device.action.BOND_STATE_CHANGED")) {
byte[] pin;
try {
pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, DEVICE_PIN);
BluetoothDevice.class.getMethod("setPin", byte[].class).invoke(device, pin);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
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) {
//Continue work here....
//If the number of paired devices greater than 3, unpair everything except the current one...
//Causing problem in lenovo tablet...
//Problem :- Tablet hang for more than 4 paired devices...
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices;
mPairedDevices = btAdapter.getBondedDevices();
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String deviceAddress = pref.getString("BL", "NoDevice");
if (mPairedDevices.size() > MAX_ALLOWED_PAIRED_DEVICES) {
// findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (final BluetoothDevice deviceForLoop : mPairedDevices) {
//if the device for loop doesn't match the latest saved address...
//unpair the device...
if(!deviceAddress.equals(deviceForLoop.getAddress())){
isUnpairToastToBeDisplayed = false;
unpairDevice(deviceForLoop);
isUnpairToastToBeDisplayed = true;
}
}
}
showToast(getString(R.string.pairedToastMessage),false);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
if(!isUnpairToastToBeDisplayed)
showToast(getString(R.string.unpairedToastMessage),false);
}
}
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
Intent i = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(i);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InvocationTargetException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
}
};
private void unpairDevice(final BluetoothDevice device) {
try {
final Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (final Exception e) {
// Log.e(TAG, e.getMessage());
}
}
public class ConnectThread extends Thread {
private final String address;
private boolean connectionStatus;
ConnectThread(final String MACaddress) {
this.address = MACaddress;
this.connectionStatus = false;
}
#Override
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(this.address);
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);
try {
SPP_UUID = device.getUuids()[0].getUuid();
BluetoothSocket tmp = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
Class<?> clazz = tmp.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
mBtSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
} catch (final IOException e) {
this.connectionStatus = false;
} catch (Exception e) {
}
} catch (final IllegalArgumentException e) {
this.connectionStatus = false;
}
try {
mBtSocket.connect();
this.connectionStatus = true;
} catch (final IOException e1) {
try {
mBtSocket.close();
Log.d("check", "check");
} catch (final IOException e2) {}
}
// Create a data stream so we can talk to server.
try {
mOutStream = mBtSocket.getOutputStream();
} catch (final IOException e2) {
this.connectionStatus = false;
}
// Send final result
if (this.connectionStatus) {
mHandler.sendEmptyMessage(1);
} else {
mHandler.sendEmptyMessage(0);
}
}
}
}
I found the answer in the following question:-
IOException: read failed, socket might closed - Bluetooth on Android 4.3
Actually I had to use reflection only on the fall back, ie, inside the catch when the connect fails.

Android Bluetooth Paring Input Device

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

Categories

Resources