Monitoring the connection of a paired bluetooth device - android

I have written the code which returns me a list of all the paired bluetooth devices of a android device.One among the list of paired bluetooth devices is my laptop as well.
Now my question is
Is there a way I can monitoring the bluetooth connectivity status between the laptop and the android device.The output which I need is "Connected" if there is a bluetooth connection present and "Disconnected" if there is no bluetooth connection
The android version is 2.1.Eclair
Before I proceed further , I have some questions.
->Should I test this application when I connect the laptop and device through USB?
->How to run it on a separate thread or from an AsyncTask?
->The above code is not working for me if I connect the device and the laptop through USB and then launch the application. Even though the laptop and the phone are nearby and they are paired, I am not able to see a connected status in the phone.
The code which I have written is as follows
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_);
out = (TextView) findViewById(R.id.textView1);
// Getting the Bluetooth adapter
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
// out.append("\nAdapter: " + adapter);
// Check for Bluetooth support in the first place
// Emulator doesn't support Bluetooth and will return null
if (adapter == null) {
out.append("\nBluetooth NOT supported. Aborting.");
return;
}
// Starting the device discovery
out.append("\nStarting discovery...");
adapter.startDiscovery();
out.append("\nDone with discovery...");
// Listing paired devices
out.append("\nDevices Pared:");
Set<BluetoothDevice> devices = BluetoothAdapter.getDefaultAdapter()
.getBondedDevices();
for (BluetoothDevice device : devices) {
out.append("\nFound device: " + device);
out.append("\n The name is: " + device.getName());
out.append("\n The type is: "
+ device.getBluetoothClass().getDeviceClass());
Method m;
try {
System.out.println("Trying to connect to " + device.getName());
m = device.getClass().getMethod("createInsecureRfcommSocket",
new Class[] { int.class });
BluetoothSocket socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
out.append("Connected");
} catch (Exception e) {
e.printStackTrace();
out.append("\nDisconnected");
}
}
}

Which android version you are using?
You must have the permission on your AndroidManifest.xml:
<uses-permission android:name="android.permission.BLUETOOTH" />
You can try the code below, but be sure to run it on a separate thread or from an AsyncTask or your UI can hang up.
This will check for your paired devices and try to connect to each one. If it is successful then it prints Connected on logcat or else it prints Disconnected.
private void checkPairedPrinters() throws IOException {
Set<BluetoothDevice> devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
for (BluetoothDevice device : devices) {
Method m;
try {
System.out.println("Trying to connect to " + device.getName());
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
BluetoothSocket socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
System.out.println("Connected");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Disconnected");
}
}
}

Related

Android bluetooth connection to ELM327/OBD2 device

I tried to create a simple android application to connect to my ELM327 device to get some car diagnostic data. But I wasn't able to set up the bluetooth connection b/t my android phone and my ELM327 device.
My code is very simple as below:
public class Bluetooth {
protected BluetoothAdapter mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
private ConnectThread mConnectThread = null;
private AcceptThread mAcceptThread = null;
private WorkerThread mWorkerThread = null;
private BluetoothDevice mOBDDevice = null;
private BluetoothSocket mSocket = null;
private String uuid;
Bluetooth() {
mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices;
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled())
return;
pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
//TODO: check whether this is OBD and whether it is connected
//by sending a command and check response
if (deviceName.contains("OBD")) {
mOBDDevice = device;
uuid = device.getUuids()[0].toString();
break;
}
}
}
mBluetoothAdapter.cancelDiscovery();
}
/**
* Start the chat service. Specifically start AcceptThread to begin a session
* in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void connect()
{
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
mSocket = mOBDDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
try {
mSocket.close();
} catch (IOException closeException) {
Log.e(TAG, "Could not close the client socket", closeException);
}
return;
}
}
}
In the mainactivity, I will first new a Bluetooth class then call bluetooth.connect():
mBluetooth = new Bluetooth();
mBluetooth.connect();
When I debug the program, I was able to get my ELM327 bluetooth device by querying all the bonded devices with a name of "OBD". I also was able to get the device's uuid and create a socket using createRfcommSocketToServiceRecord. But in the connect function, mSocket.connect() always fail with a return value of -1 and get a IOexception.
My questions are:
When my android application connect to the ELM327 device, my android phone is the bluetooth client and my ELM327 device is the bluetooth server, is this understanding correct?
Is there a server program running on my ELM327 device listening and accept incoming connection? Is this defined behavior of ELM327 protocol?
Any idea why mSocket.connect()has failed? Any idea on how to look into this issue? Or any obvious error in my program? Thanks.
problem solved. see source codes below:
public synchronized void connect() throws IOException {
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
mSocket = mOBDDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mSocket.connect();
} catch (IOException e1) {
Log.e(TAG, "There was an error while establishing Bluetooth connection. Falling back..", e1);
Class<?> clazz = mSocket.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
try {
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[]{Integer.valueOf(1)};
mFallbackSocket = (BluetoothSocket) m.invoke(mSocket.getRemoteDevice(), params);
mFallbackSocket.connect();
mSocket.close();
mSocket = mFallbackSocket;
} catch (Exception e2) {
Log.e(TAG, "Couldn't fallback while establishing Bluetooth connection.", e2);
mSocket.close();
//throw new IOException();
}
}
inputStream = mSocket.getInputStream();
outputStream = mSocket.getOutputStream();
}
I don't know much about Android, although I know about OBD2 and the lot.
It depends on the type of your adapter. If you have a WiFi adapter, you can consider the adapter being the server and you the client. You connect to a socket and then read from it. In the case of a Bluetooth adapter, it's different. If you connect via rfcomm, it's a serial protocol and neither is the server nor the client. If you connect via BTLE, the OBD2 dongle is the Peripheral and you are the Central.
On WiFi adapters, yes. This behavior is not part of ELM327 though. ELM327 only specifies the serial commands. How you transfer these is not part of the spec, since it happens on the layer above (WiFi, rfcomm, BTLE, USB, etc.).
Are you sure that rfcomm works via the socket interface? It's a serial interface, so I would have expected file-like operations.

BLE - First connection with app is not working

I'm working with device Texas, for management of the LED, in my custom Android app. The device has enabled the pairing with a default passkey 000000. In my code for app, I have this part of code for reading the paired of device.
private void getpaireddevices(){
Set<BluetoothDevice> devicesArray = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if(devicesArray.size() > 0) {
for(BluetoothDevice device : devicesArray) {
device.getName();
device.getAddress();
}
}
}
In this moment, when I enable the BLE the app found the device, it connect but not works. For this to work I should exit and reconnect with my device. Why?
This is possible if the device is already bonded. Call removeBond() method to clear previous bonding state.
device.removeBond();
For check bonding state of BluetoothDevice, use getBondState().
Ble gatt connection success rate is different per device by device. You may need disconnect ble by hidden method, if your connection fails continuously.
Please read this:
BLE Device Bonding Remove Automatically in Android
The method unpairDevice() will unpair bluetooth connection.
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice bt : pairedDevices) {
if (bt.getName().contains("String you know has to be in device name")) {
unpairDevice(bt);
}
}
// Function to unpair from passed in device
private void unpairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) { Log.e(TAG, e.getMessage()); }
}

Failing bluetooth sequence

I'm trying to make a simple connection sequence to a serial bluetooth device at the beginning of my app. Right now, all of this is inside onCreate ():
BT = BluetoothAdapter.getDefaultAdapter();
BT.enable();
if(!BT.isEnabled()) {
Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler, REQUEST_ENABLE);
BT.enable();
Toast.makeText(getApplicationContext(), "Bluetooth On.", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else {
Toast.makeText(getApplicationContext(), "Bluetooth On.", Toast.LENGTH_LONG).show();
}
pairedDevices = BT.getBondedDevices();
pDevices = new ArrayList<BluetoothDevice>();
if (pairedDevices.size()>0) {
for(BluetoothDevice bt : pairedDevices)
{
pDevices.add(bt); //Get the device's name and the address
}
}
else {
Toast.makeText(getApplicationContext(), "Nothing paired.", Toast.LENGTH_LONG).show();
}
try {
BluetoothDevice dispositivo = BT.getRemoteDevice(pDevices.get(0).getAddress());
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);
btSocket.connect();
}
catch (IOException e){
Toast.makeText(getApplicationContext(), "Failed.", Toast.LENGTH_LONG).show();
}
The goal is to connect to the first available paired device. So far it always displays "Failed." even when I have an unconnected paired device sitting next to the phone.
Should I be doing this somewhere else in the app? I'm not really concerned with delaying the main activity since this is for a personal project.
Edit: spelling
All BT 2.1 devices and newer ones require the secure connection, so use the createRfcommSocketToServiceRecord instead of the createInsecureRfcommSocketToServiceRecord.
I actually figured it out... It was trying to connect to only the first paired connection. I put the try catch on a for loop, now it connects fine :)

Bluetooth Connection: insecure connections, secure connections, listening securely or insecurely, what to use?

I'm struggling with getting consistent bluetooth connections in a star topology. I have one master phone which is a Samsung Galaxy S4 running API 10. All of the phones that connect to the bluetoothserver socket on the S4 are LG Dynamic Tracfones also running API 10.
Over the past few days, I have seen a LOT of conflicting information on the web about what type of connection to use.
This is my current set up:
MASTER CODE
public void acceptConnection() {
.... (enable bt adapter) ...
// initializes a Bluetooth server socket
bluetoothServerSocket = bc.createBluetoothServerSocket();
//connection made to Master, discovery no longer needed
bluetoothAdapter.cancelDiscovery();
BluetoothSocket bluetoothSocket;
// loops until the thread is interrupted or an exception occurs
while (!isInterrupted()) {
try {
// attempts to accept the slave application's connection
bluetoothSocket = bluetoothServerSocket.accept();
} catch (IOException e) {
// prints out the exception's stack trace
e.printStackTrace();
Log.v("Default Thread", "Connection to slave failed.");
// breaks out of the while loop
return;
}
try {
... (enumerate all input and output streams, and all bt sockets) ...
} catch (IOException e) {
// prints out the exception's stack trace
e.printStackTrace();
}
}
This is the method that is called when creating a blueToothServerSocket, and this is where half of my confusion is. How should I listen on the adapter? Currently, I'm doing it insecurely.
public BluetoothServerSocket createBluetoothServerSocket() {
// gets the name of the application
String name = "PVCED";
// gets a common UUID for both the master and slave applications
UUID uuid = UUID.fromString("23ea856c-49da-11e4-9e35-164230d1df67");
// initializes an empty Bluetooth server socket
serverSocket = null;
try {
// creates a Bluetooth socket using a common UUID
serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(name, uuid);
} catch (IOException e) {
// prints out the exception's stack trace
e.printStackTrace();
}
return serverSocket;
}
SLAVE CODE
And this is where the other half of my confusion is, how should I create a socket? Currently I'm doing it insecurely.
private BluetoothSocket createBluetoothSocket(Set<BluetoothDevice> pairedDevices) {
// gets a common UUID for both the master and slave applications
UUID uuid = UUID.fromString("23ea856c-49da-11e4-9e35-164230d1df67");
// initialises an empty Bluetooth socket
BluetoothSocket bluetoothSocket = null;
// checks to see if there are any paired devices
if (pairedDevices.size() > 0) {
// loops through each paired device
for (BluetoothDevice device : pairedDevices) {
// checks to see if the name of the paired device is MASTER
if (device.getName().equals("MASTER")) {
try {
master = device;
// creates a Bluetooth socket using a common UUID
//bluetoothSocket = master.createRfcommSocketToServiceRecord(uuid);
//Method m = master.getClass().getMethod("createRfcommSocketToServiceRecord", new Class[] {int.class});
//bluetoothSocket = (BluetoothSocket) m.invoke(master, 1);
bluetoothSocket = master.createInsecureRfcommSocketToServiceRecord(uuid);
} catch(Exception e){
Log.v("Connect Exception", e.getMessage());
}
}
}
}
//check if we paired succesfully to a master, if not, prompt user to do so.
if (master == null){
... (tell user to pair with master via toast) ...
}
return bluetoothSocket;
}
My logcat is often filled with errors such as "Bad File Descriptor", "Unable to start Service Discovery", or "Service Discovery has failed."
What is the best connection scheme to use for my scenario? If you guys need more details on how I'm enabling/disabling bt adapters, or closing bt connections, I can supply more code.

Bluetooth issues on HTC hero

I've written an android application getting data from external sensors using Bluetooth. It's working fine on Sony Ericsson XPERIA but not on a HTC Hero (it finds external devices but it can't get any data from them) I'm wondering why. After some research on the net, I still haven't found any clue.
Anyone had similar bluetooth issues on HTC?
you can make it like this:
private final String PBAP_UUID = "0000112f-0000-1000-8000-00805f9b34fb"; //standard pbap uuid
mSocket = mDevice.createInsecureRfcommSocketToServiceRecord(ParcelUuid.fromString(PBAP_UUID).getUuid())
mSocket.connect();
Just do it.
If I remember correctly the HTC phones had or [have] an issue at a certain API level (maybe 2.1 and below?). The resolution is reflection.
Reference
Disconnect a bluetooth socket in Android
Service discovery failed exception using Bluetooth on Android
Solution
Instead of using
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
use
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
to get your BluetoothSocket on certain HTC phones using a certain API level.
Solution Expanded
I recently had an application where I had to account for this, and I did not like using this on non-HTC phones, so I had a conditional to check for HTC, if true then use reflection, otherwise dont.
public BTConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the given BluetoothDevice
if (isAnHTCDevice())
{
try
{
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
}
catch (Exception e)
{
Log.e(BCTAG, "Error at HTC/createRfcommSocket: " + e);
e.printStackTrace();
handler.sendMessage(handler.obtainMessage(MSG_BT_LOG_MESSAGE, "Exception creating htc socket: " + e));
}
}
else
{
try
{
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (Exception e)
{
Log.e(BCTAG, "Error at createRfcommSocketToServiceRecord: " + e);
e.printStackTrace();
handler.sendMessage(handler.obtainMessage(MSG_BT_LOG_MESSAGE, "Exception creating socket: " + e));
}
}
mmSocket = tmp;
}
isAnHTCDevice():
public boolean isAnHTCDevice()
{
String manufacturer = android.os.Build.MANUFACTURER;
if (manufacturer.toLowerCase().contains("htc"))
return true;
else
return false;
}
you can make it like this:
private final String PBAP_UUID = "0000112f-0000-1000-8000-00805f9b34fb"; //standard pbap uuid
mSocket = mDevice.createInsecureRfcommSocketToServiceRecord(ParcelUuid.fromString(PBAP_UUID).getUuid());
mSocket.connect();
Just do it.

Categories

Resources