How to get connected Bluetooth device data in android? - android

I'm developing an app to receive Bluetooth commands from Bluetooth remote. So the requirement is whenever user clicks a button, I should toast that button Key_Code. I've tried to access the Bluetooth_Service through BluetoothManager class, but there is no access to that part. Please do help me.
MyCode to getBluetoothDevices:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
String str = "";
for (BluetoothDevice device : pairedDevices) {
mDevice = device;
str = str+mDevice.getName()+", ";
}
}else{
System.out.println("No devices Found");
}
I'm getting the device name and mac address etc, but there isn't a binder for the receiving of commands

There are two ways to do that.
If you want to receive the KEY_CODES of android remote from your Activity, you can directly call the below method. It will give you all the keycodes of the buttons pressed.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Toast.makeText(this,"KeyCode is"+keyCode,Toast.LENGTH_LONG).show();
return super.onKeyDown(keyCode, event);
}
Note: This cannot be possible with an android service.
Write a Bluetooth Socket that connects with Your own BluetoothServer and Start communicating.
Client:
private class ClietnThread extends Thread{
ClietnThread(BluetoothDevice dev){
mDevice= dev;
}
#Override
public void run() {
super.run();
Log.e(Tag,"Now CONNECTING to"+mDevice.getName());
try{
//mBluetoothSocket =(BluetoothSocket) mDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mDevice,1);
mBluetoothSocket = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
mBluetoothSocket.connect();
}catch (IOException e){
Log.e(Tag,"Connect Failed");
e.printStackTrace();
try {
mBluetoothSocket.close();
} catch (IOException closeException) {
Log.e("Client", "Could not close the client socket", closeException);
}
}
}
}
Server:
private class MyServer extends Thread{
MyServer(){
}
#Override
public void run() {
super.run();
Log.e(Tag,"Bluetooth Listening");
try {
mBluetoothServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
mBluetoothAdapter.cancelDiscovery();
}catch (IOException e){
e.printStackTrace();
}
while (true){
try{
BluetoothSocket mSoicket = mBluetoothServerSocket.accept();
Log.e(Tag,"ConnectedToSpike");
}catch (IOException e){
e.printStackTrace();
}
}
}
}

Related

BluetoothDevice.ACTION_ACL_DISCONNECTED never called despite the bluetoothsocket is closed

I have two devices connected through Bluetooth now. After that, I disconnected the Bluetooth connection on the Client device, and the broadcast receiver in this Client device can detect the disconnection, and then switch it back to previous activity. Something like this:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
try {
Log.i("Disconnecting3", "Disconectinggg....");
Intent intent1 = new Intent(Main3Activity.this, MainActivity.class);
startActivity(intent1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
Anyhow, on my other device which is the Server device, this device CAN NOT detect the disconnection despite the Bluetooth socket is closed! The broadcast receiver in the Server device cannot detect the disconnection. FYI, below code will show how I close the Bluetooth socket on the Server device when the Client device is disconnected.
private boolean CONTINUE_READ_WRITE;
CONTINUE_READ_WRITE = true;
public void run() {
try {
while (CONTINUE_READ_WRITE) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = handleSeacrh.obtainMessage(MessageConstants.MESSAGE_READ, numBytes, -1, mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
//nothing();
CloseConnection closeConnection = new CloseConnection();
closeConnection.start();
break;
}
}
} catch (Exception e) {
// Log.d(TAG, "Input stream was disconnected", e);
}
}
public void cancel() {
try {
Log.i("TAG", "Trying to close the socket");
CONTINUE_READ_WRITE = false;
mBluetoothSocket.close();
mmBluetoothSocket.close();
Log.i("TAG", "I thinked its still closing");
} catch (IOException e) {
Log.e("TAG", "Could not close the connect socket", e);
}
}
So when there is a disconnection happened on the Client device, the while(CONTINUE_READ_WRITE)..loop will break the loop and start a new Thread. Something like this :
private class CloseConnection extends Thread {
public void run(){
Log.i("Running","Runinnggggg");
try {
mmInStream.close();
mmOutStream.close();
bluetoothDataTransmission.cancel();
Log.i("Interrupted","InteruppteDDDD");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Alright, I found a solution , just need to add this line of code
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

How to programmatically pair and connect a HID bluetooth device(Bluetooth Keyboard) on Android

I am able to pair a bluetooth keyboard but not able to connect so as to make it an input device.
I went through the documentation provided at developer site - http://developer.android.com/guide/topics/connectivity/bluetooth.html#Profiles
It says that the Android Bluetooth API provides implementations for the following Bluetooth profiles but you can implement the interface BluetoothProfile to write your own classes to support a particular Bluetooth profile.
Headset
A2DP
Health Device
There is no documentation how to implement BluetoothProfile for HID bluetooth device(Keyboard)
Android has itself implemented bluetooth connection for HID devices but those API's are hidden. I tried reflection to use them too. I do not get any error but keyboard does not get connected as input device. This is what i have done -
private void connect(final BluetoothDevice bluetoothDevice) {
if(bluetoothDevice.getBluetoothClass().getDeviceClass() == 1344){
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Log.i("btclass", profile + "");
if (profile == getInputDeviceHiddenConstant()) {
Class instance = null;
try {
//instance = Class.forName("android.bluetooth.IBluetoothInputDevice");
instance = Class.forName("android.bluetooth.BluetoothInputDevice");
Method connect = instance.getDeclaredMethod("connect", BluetoothDevice.class);
Object value = connect.invoke(proxy, bluetoothDevice);
Log.e("btclass", value.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
#Override
public void onServiceDisconnected(int profile) {
}
};
mBluetoothAdapter.getProfileProxy(this, mProfileListener,getInputDeviceHiddenConstant());
}
}
public static int getInputDeviceHiddenConstant() {
Class<BluetoothProfile> clazz = BluetoothProfile.class;
for (Field f : clazz.getFields()) {
int mod = f.getModifiers();
if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod)) {
try {
if (f.getName().equals("INPUT_DEVICE")) {
return f.getInt(null);
}
} catch (Exception e) {
Log.e("", e.toString(), e);
}
}
}
return -1;
}
Due to security reasons, it is not possible for third party applications to connect to a bluetooth keyboard as the application can be a keylogger. So it can be only done manually by the user.
Here is the code I used on Android Marshmallow (6.0).. To get an L2CAP connection started (Needed for HID)
public static BluetoothSocket createL2CAPBluetoothSocket(String address, int psm){
return createBluetoothSocket(BluetoothSocket.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){
Log.e(TAG, "Creating socket with " + address + ":" + 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) {
e.printStackTrace();
}
return null;
}
public Boolean connect(View v) {
try {
// TODO: Check bluetooth enabled
mDevice = getController();
if (mDevice != null) {
Log.e(TAG, "Controller is paired");
// Create socket
mSocket = createL2CAPBluetoothSocket(mDevice.getAddress(), 0x1124);
if (mSocket != null) {
if (!mSocket.isConnected()) {
mSocket.connect();
}
Log.e(TAG, "Socket successfully created");
ConnectedThread mConnectedThread = new ConnectedThread(mSocket);
mConnectedThread.run();
}
} else {
showToast("Controller is not connected");
}
return true;
} catch (Exception e) {
e.printStackTrace();
if (e instanceof IOException){
// handle this exception type
} else {
// We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
}
return false;
}
}
private BluetoothDevice getController() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("Wireless Controller")) // Change to match DS4 - node name
{
Log.d(TAG, "Found device named: " + device.getName());
return device;
}
}
}
return null;
}
It can still have problems creating the Service, and you need to set the correct L2CAP PSAM for the device, but hope it can help..

set bluetooth authentication PIN when listening from adapter

I'm making an app that needs to connect with a bluetooth device and get data from it... that device is set as master, so I needed to implement a Thread, where I listenUsingRfcommWithServiceRecord and wait for a connection from it:
public AcceptThread(Context context, String serverName, UUID myUUID) {
this.context = context;
BluetoothServerSocket tmp = null;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(serverName, myUUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
Then on run I run the code socket = mmServerSocket.accept(5000) to wait until it starts pairing with the device:
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = mmServerSocket.accept(5000);
} catch (IOException e) {
Log.e(TAG,"IOException: " + e);
}
// If a connection was accepted
if (socket != null) {
// Manage the connection
ManageConnectedSocket manageConnectedSocket = new ManageConnectedSocket(socket);
manageConnectedSocket.run();
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "IOException: " + e);
}
break;
}
}
}
The Device asks for an authentication PIN, and I need to have an automatic procedure... for that I though of implementing a broadcast receiver to know when the device is asked to par with another device:
IntentFilter filter = new IntentFilter(ACTION_PAIRING_REQUEST);
context.registerReceiver(mPairReceiver, filter);
and receive it:
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_PAIRING_REQUEST.equals(action)) {
Log.e(TAG,"ACTION_PAIRING_REQUEST");
setBluetoothPairingPin(device);
}
}
};
In my setBluetoothPairingPin method I receive a BluetoothDevice object :
public void setBluetoothPairingPin(BluetoothDevice device) {
byte[] pinBytes = convertPinToBytes("0000");
try {
Log.e(TAG, "Try to set the PIN");
Method m = device.getClass().getMethod("setPin", byte[].class);
m.invoke(device, pinBytes);
Log.e(TAG, "Success to add the PIN.");
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, false);
Log.e(TAG, "Success to setPairingConfirmation.");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
The problem is that I can't know when my socket receives information, and consecutively, can't know what is my BluetoothDevice to set Pairing Pin before it's connected...
Can someone help me on how to surpass this? Or is there other way to put the pin authentication when I'm listenning from BluetoothServerSocket?
If I'm not explaining correctly, please let me know...
Thanks in advance
With the help from this and this, I was able to make work for me...
My confusion was with the method setBluetoothPairingPin that I couldn't understand that the ACTION_PAIRING_REQUEST is actually called when the device is being starting to pairing, and that is when the PIN is asked from the user... so invoking BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);, and changing a bit of the set pairing method I manage to make it work...
Here's my final code:
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_PAIRING_REQUEST.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String PIN = "0000";
byte[] pin = new byte[0];
try {
pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, PIN);
BluetoothDevice.class.getMethod("setPin", byte[].class).invoke(device, pin);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}

Can't send data to Arduino Due from Android via Bluetooth

I have written an Android app that's supposed to send data to Arduino Due via Bluetooth Module (ZS-040). Bluetooth connection is fine. However, Arduino doesn't seem to receive any data from Android. When I send data to Arduino through the Serial Monitor though, it works. I've looked into many stackoverflow questions and other guides online but can't seem to figure out what's wrong.
Here's some code:
Thread for connecting the two devices:
private class ConnectThread extends Thread {
private BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//uuid for Arduino bluetooth module
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { };
socket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
runOnUiThread(new Runnable() {
#Override
public void run() {
findBtn.setText("Search for devices");
}
});
try {
socket.connect();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException connectionException) {
try {
socket.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "An error has occured. Please try again.",
Toast.LENGTH_SHORT).show();
}
});
} catch (IOException closeException) { }
return;
}
}
}
Code for sending data to Arduino; function is called when a button is pressed.
public void sendData(View view) {
// write to OutputStream
OutputStream mmOutputStream = null;
try {
mmOutputStream = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}
// String message = "0";
// byte[] msgBuffer = message.getBytes();
try {
mmOutputStream.write('0');
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}
}
Arduino code (directly copied from here):
char incomingByte; // incoming data
int LED = 12; // LED pin
void setup() {
Serial.begin(9600); // initialization
pinMode(LED, OUTPUT);
Serial.println("Press 1 to LED ON or 0 to LED OFF...");
}
void loop() {
if (Serial.available() > 0) { // if the data came
incomingByte = Serial.read(); // read byte
if(incomingByte == '0') {
digitalWrite(LED, LOW); // if 1, switch LED Off
Serial.println("LED OFF. Press 1 to LED ON!"); // print message
}
if(incomingByte == '1') {
digitalWrite(LED, HIGH); // if 0, switch LED on
Serial.println("LED ON. Press 0 to LED OFF!");
}
}
}
EDIT: Because it's a DUE with which I'm working, I can't use SoftwareSerial library. :(
I've figured it out after much debugging with both hardware and software. Serial refers to rx0 and tx0 on the Due board. However, when the board is powered by the computer via usb cable (usb-to-serial to be exact), rx0 receives data from the computer instead of the bluetooth even when it's connected. Changing it to other serial such as Serial1 (rx1 and tx1), Serial2 (rx2, tx2) and Serial3 (rx3, tx3) in the Arduino code prevents that from happening.

Bluetooth paired devices connection problems

I'm having issues with connecting. At first it works, than it does not, unless I unpair the devices.
I've gotten every possible exception that could happen, socket closed, pipe closed, connection refused, port already in use, etc.
I'm aware that there are issues with bluetooth on android pre 4.2 (https://code.google.com/p/android/issues/detail?id=37725).
Devices that I'm having problems with connecting these devices:
Htc one(android 4.2)
samsung galaxy s2(android 4.1.2)
nexus 4 (4.3)
samsung galaxy s4 (4.2)
Another minor issue is, that the paired devices are not stored (mostly on the nexus 4, and the sgs2).
Here is my code:
private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //this is the other one that I've tried: fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME = "BluetoothConnector";
public void listenForConnection() throws IOException, BluetoothException {
//first close the socket if it is open
closeSocket();
BluetoothServerSocket mServerSocket = null;
try {
mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID_SECURE); //ioexception here!
} catch (IOException e) {
if (Build.VERSION.SDK_INT >= 9) {
try { //this is a stupid hack, http://stackoverflow.com/questions/6480480/rfcomm-connection-between-two-android-devices
Method m = mBluetoothAdapter.getClass().getMethod("listenUsingRfcommOn", new Class[] { int.class });
mServerSocket = (BluetoothServerSocket) m.invoke(mBluetoothAdapter, PORT);
} catch (Exception ex) {
Log.e(ex);
throw e;
}
} else {
throw e;
}
}
while (!isCancelled) {
try {
socket = mServerSocket.accept();
} catch (IOException e) {
if (socket != null) {
try {
socket.close();
} finally {
socket = null;
}
}
throw e;
}
if (socket == null) {
throw new BluetoothException("Socket connection connected, but null");
} else {
isConnected = true;
break; // everything is ok
}
}
}
public void connect(String address) throws IOException, BluetoothException {
mBluetoothAdapter.cancelDiscovery();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} catch (IOException e1) {
Log.e(e1);
if (Build.VERSION.SDK_INT >= 9) {
try {
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(device, PORT);
} catch (Exception e) {
Log.e(e);
throw e1;
}
} else {
throw e1;
}
}
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
} catch (IOException e) {
Log.e(e);
// Close the socket
try {
socket.close();
} catch (IOException e2) {
Log.e(e2);
Log.wtf("unable to close() socket during connection failure");
}
throw e;
}
}
private void closeSocket() {
try {
if (socket != null) {
socket.close();
socket = null;
Log.d("Socket closed");
}
} catch (IOException e) {
Log.e(e);
Log.wtf("close() of connect socket failed");
}
}
I tried changing the uuid(random one also), tried looking at older sdk samples.
So what could be wrong here?
edit: trying to clarify: the problem usually comes up, when 2 devices that have been paired, connected, did some successful communication, get disconnected (by the user). After that, they can not be reconnected, unless they get rebooted, or unpaired manually.
You are trying to paired this manner:
private void TwitPairedDevice() {
buttonTwitPairDevice.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> fetchPairedDevices=bluetooth.getBondedDevices();
Iterator<BluetoothDevice> iterator=fetchPairedDevices.iterator();
while(iterator.hasNext())
{
final BluetoothDevice pairBthDevice=iterator.next();
final String addressPairedDevice=pairBthDevice.getAddress();
AsyncTask<Integer, Void, Void> asynchPairDevice=new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
try {
socket=pairBthDevice.createRfcommSocketToServiceRecord(uuid);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
};asynchPairDevice.execute();
}
}
});
}
Connect Pired Device:
private void FetchPairedDevices() {
Set<BluetoothDevice> pairedDevices=bluetooth.getBondedDevices();
for(BluetoothDevice pairedBthDevice:pairedDevices)
{
listPairedDevice.add(pairedBthDevice.getName());
}
listviewPairedDevice.setAdapter(adapterPairedDevice);
listviewPairedDevice.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Object listPairedName=arg0.getItemAtPosition(arg2);
String selectedPairedName=listPairedName.toString();
Set<BluetoothDevice> bthDeviceChecking=bluetooth.getBondedDevices();
for(final BluetoothDevice bthDevice:bthDeviceChecking)
{
if(bthDevice.getName().contains(selectedPairedName))
{
listPairDevice.clear();
listPairDevice.add(bthDevice);
final String addressPairedDevice=bthDevice.getAddress();
AsyncTask<Integer, Void, Void> asynTask=new AsyncTask<Integer,Void,Void>() {
#Override
protected Void doInBackground(Integer... params) {
try {
socket=bthDevice.createRfcommSocketToServiceRecord(uuid);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
asynTask.execute(arg2);
}
}
}
});
}
It seems that at this point Bluetooth is broken on android.
There is no sure way of connecting 2 devices, that works all the time.
Some people are using an unofficial way to do it, but that does not work on all devices.
I did some in house testing, with the top 10 devices, that are on the market currently, so after around around 90 test runs, the hacked method worked 75% of the time, which is not good enough.
For example, the htc oneX will just handle incoming Bluetooth request, as a Bluetooth hands free device(it is connecting succesfully!), but makes messaging impossible.
After implementing full Bluetooth functionality, we decided to remove it from our app, and release it without it. We'll switch to wifi in some later release.

Categories

Resources