Bluetooth Pairing Google Glass - android

Using Google Glass, I am able to discover Bluetooth devices and see their address and information. However, I cannot get the Glass to pair (bond) with them.
Update
Following the instructions on this page now I'm trying to get the bonding, but for some reason the BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action) is never happening.
private void pairDevice(BluetoothDevice Ddevice) {
Log.d("MY_LOG", "Try to pair " + Ddevice.getName());
try{
Method m = Ddevice.getClass().getMethod("createBond", (Class[]) null);
m.invoke(Ddevice, (Object[]) null);
Log.d("MY_LOG", "Pairing " + Ddevice.getName());
}catch(Exception e){
Log.d("MY_LOG", "Error: ");
e.printStackTrace();
}
}
In the LOG I always get "Pairing DeviceName" but when I search for the bonded devices, it remains empty.
Any help will be greatly appreciated.

So I will answer my own question as I just found the way.
So first, the discovery of devices is quite easy, in onCreate() I used (besides all other sort of code you need):
MyBT = BluetoothAdapter.getDefaultAdapter();
MyBT.startDiscovery();
Filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); // Register the BroadcastReceiver
Filter2 = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST); // Register the Bond changing state
registerReceiver(mReceiver, Filter); // Don't forget to unregister during onDestroy
registerReceiver(mReceiver, Filter2); // ******
Then at the BroadcastReceiver you need to manage the devices and the pairing requests:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { // Create a BroadcastReceiver for ACTION_FOUND
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) { // When discovery finds a device
BluetoothDevice BTdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Get the BluetoothDevice object from the Intent
ListDev.add(BTdevice); // Add the device to an array adapter to show...
}
if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
BluetoothDevice device = ListDev.get(selectedDevice);
byte[] pinBytes = getStrFromName(device.getName(),7,11).getBytes(); // My devices had their own pin in their name, you can put a constant pin here...
try {
Log.d("MY_LOG", "Try to set the PIN");
Method m = device.getClass().getMethod("setPin", byte[].class);
m.invoke(device, pinBytes);
Log.d("MY_LOG", "Success to add the PIN.");
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
Log.d("MY_LOG", "Success to setPairingConfirmation.");
} catch (Exception e) {
Log.e("MY_LOG", e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
Log.e("MY_LOG", e.getMessage());
e.printStackTrace();
}
}
}
};
After that the device is bonded and you can manage the connection with the UUID and the sockets just as in the Android webpage example.
Hope this helps!

Related

How to connect bluetooth with default pin "0000"-Unable to pair

To connect a Bluetooth device with embedded device,I want user's click on discovered device and auto pair with 0000 pin (No need for confirmation and also important 0000 passkey), not with creating bond with passkeys,I don't have any connection related issue
I found following code I am not sure its working or not also don't know on how to pair Device(phone) to another device(Embedded device) with pin="0000" in this code??
Here is some part of code for connectivity.
OnItemClicklistner on discoverd(scanned ) devices
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
IntentFilter filter = new IntentFilter(
"android.bluetooth.device.action.PAIRING_REQUEST");
registerReceiver(mPairingRequestReceiver, filter);
}
This is my pairing Receiver for connection with 0000 pin
private final BroadcastReceiver mPairingRequestReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
try {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0);
//the pin in case you need to accept for an specific pin
String pin="0000";
Log.d(TAG, "Start Auto Pairing. PIN = " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",0));
byte[] pinBytes;
// pinBytes = (""+pin).getBytes("UTF-8");
pinBytes = pin.getBytes();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
device.setPin(pinBytes);
device.setPairingConfirmation(true);
}
} catch (Exception e) {
Log.e(TAG, "Error occurs when trying to auto pair");
e.printStackTrace();
}
}
}
};
Note : Creat bond is working here. I dont want to creat bond just on click Item and connect to embedded device with 0000 pin.... Thank you..

Auto determine the bluetooth device is OBD or not?

Current I am working on OBDII. While in bluetooth discovery to connect obd, How I determine which device is obd and which device is normal bluetooth device.Because I want auto connect my app with obd.
Is there any common characteristic of obd device which help me to determine this is OBD device?
My Code which I am trying for pairing obd device as per name.
//Register receiver for bluetooth discovery
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismiss progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found for pair
try {
// Here I want to know device is obd or not?
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Make pair of obd device as per name:
if (device != null && !device.getName().equals("")) {
LogUtils.LOGE("NEW DEVICE", device.getName());
if (device.getName().equals(OBD_DEVICE_NAME_ONE) ||
device.getName().equals(OBD_DEVICE_NAME_TWO) ||
device.getName().equals(OBD_DEVICE_NAME_THREE)) {
pairDevice(device);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
//Send pairing request to OBD Device
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
After Pairing OBD Device with name, It will autoconnect and work fine.
Only good way to find out, is to connect and to send:
ATI
Which will return a ID, which always contain ELM327.

Android Bluetooth fail when BluetoothSocket.connect

Ok, I feel like this question is still the same old ****, but I really can't figure it out after trying all the available methods from Google. This are the errors that I got:
isSocketAllowedBySecurityPolicy start : device null
getBluetoothService() called with no BluetoothManagerCallback
connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[59]}
I am trying to write a simple android program that can be used to connect to a micro-controller. I used a BroadcastReceiver to receive the discovered device. The code looks like this:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (uuidExtra == null) {
Log.d("Bluetooth", "=+=+=+=+ 1st return uuid is null.");
}
if (device.getName().equals("DeviceIWant")) {
mDevice = device;
mStatus.setText("");
mStatus.append("\n" + mDevice.getName() + "\n" + mDevice.getAddress());
}
String str = device.getName() + "\n" + device.getAddress();
Log.d("Bluetooth", "\n=+=+=+=+=+=+=+=+=+ Get in onReceive");
Log.d("Bluetooth", str);
// mBluetoothAdapter.startDiscovery();
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// Check if the desired device has been found yet.
if (mDevice != null) {
Log.d("Bluetooth", "\n=+=+=+=+ BT dev is not null.");
// If the desired device has been found, start getting the UUID
mDevice.fetchUuidsWithSdp();
}
}
if (BluetoothDevice.ACTION_UUID.equals(action)) {
Log.d("Bluetooth", "\n=+=+=+=+ BT dev uuid returned.");
// Observe the UUID
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
Parcelable uuidExtra[] = mDevice.getUuids();
if (uuidExtra == null ) {
Log.d("Bluetooth", "\n=+=+=+=+ return uuid is null.");
}
Log.d("Bluetooth", "\n=+=+=+=+ uuid Extra returned.");
// Log.d("Bluetooth", "UUID: " + uuidExtra[0].toString());
// Create the thread (it is not yet run)
mThread = new ConnectThread(mDevice);
// Start running the thread
mThread.start();
// Update the thread flag
isThreadRunning = true;
}
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
// Observe the UUID
Log.d("Bluetooth", "\n=+=+=+=+ BT dev discovery ps started.");
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// Observe the UUID
Log.d("Bluetooth", "\n=+=+=+=+ BT dev discovery ps DONE!");
}
}
};
The error occur when I try to use mSocket.connect(), where the mSocket is an instance of BluetoothSocket. The socket was created by using this line of code:
device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
The device I use is returned by the broadcast that I saved as mDevice in the above code. The creation of the socket seems to be fine. I used the very famous SPP UUID (00001101-0000-1000-8000-00805F9B34FB) to establish the connection with no luck. I also tried to obtained the UUID from the device by using
mDevice.fetchUuidsWithSdp();
follows by
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
but the problem is uuidExtra returned is always null. And when I connect the errors are the same.
I hope the problem description is clear. If any of you need more code to make the problem clearer, please let me know. Thanks for the time of reading the problems and the help!

Problems with Android Bluetooth Server and Client

I have a couple problems regarding creating a bluetooth server and client for a multiplayer game I'm making.
The first problem I have is searching for devices. Google provides following code:
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
But I can't find where mArrayAdapter is defined or how it should look like.
Second question I have is, when I have a server running on my device, do I have to connect to it also, or does only the other phone have to connect and my server acts as a client and a server?
Third question I have is how to connect to the server. Again, google provides this code:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
How do I create and use this class, and what variable should I pass for BluetoothDevice device in the constructor?
Thanks for your help :)
You can see from mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); that a String is added. So it will be defined as:
ArrayAdapter<String> mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.bluetooth_device_name);
Where did you get your code from? The complete code you can find in DeviceListActivity.java of the BluetoothChat example app which comes with the SDk for many versions again and again.
For your second question: One app on a device makes the device visible. The other app on the other device scanns for neighbouring devices and tries to connect. Then both devices have to agree.
I advise you to do the BluetoothChat app from tne examples first. It works out of the box.

How to connect Android phone & Ardunio with bluetooth to light led

I want to connect an Android phone and an Arduino Mega 2560 with bluetooth (JY-MCU) to open or close LED. Here's my Arduino code:
#include <SoftwareSerial.h>
#define arduinoRx 2
#define arduinoTx 3
int gelen_veri;
int LedCikis = 8;
SoftwareSerial bluetooth(arduinoRx,arduinoTx);
void setup()
{
bluetooth.begin(9600);
}
void loop()
{
if(bluetooth.available()>0)
{
gelen_veri=bluetooth.read();
switch(gelen_veri)
{
case 'A' :
digitalWrite(LedCikis,HIGH);
break;
case 'K' :
digitalWrite(LedCikis,LOW);
break;
default:
break;
}
}
}
In addition I have Android code:
onlight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
// String msg = "A\n";
// mmOutputStream.write(msg.getBytes()); // transmitter nesnemize 'A' karakterini ilettik.
mmOutputStream.write('A');
} catch (IOException ex) {
Log.e("hata", ex.getMessage());
}
}
});
offlight.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mmOutputStream.write('K'); // aynı şekilde transmitter nesnemize 'K' karakterini ilettik.
} catch (IOException ex) {}
}
});
}
When I debug my Android code everything is normal. But it doesn't work. Help me please.
Do you know blueArduıno? You can try and test your program & bluetooth devıce to understand where is the problem.
void findDevice() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
final Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); //daha önceden eşleşmiş cihazların listesi alındı
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("HC-06")) // JY MCU ; bizim bluetooth modulumuzun default ismi.
{
mmDevice = device; // JY-MCU bizim mmDevice nesnesimiz oldu .
break;
}
}
myLabel.setText("Bluetooth Device Found");
}
}
And
void connectBT() throws IOException {
try {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("20:13:05:06:54:98");
// Benim bluetooth modulumun MAC adresi.
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
// Standard UUID. Çok büyük ihtimalle sizinde alacağınız modulün UUID numarası aynı olacaktır
mmSocket = device.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
} catch (IOException e) {
Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
}
they are my connection methods. As debug result of android is normal, i thought that arduino code has any problem or my bluetooth device. How can i understand where is the problem???
If you are using your phone did you use any bluetooth api ?
Anyway you can try the following
Download Bluetooth chat source which is widely available
https://www.google.com.sg/search?q=bluetooth+chat+&oq=bluetooth+chat+&aqs=chrome..69i57j0l3.2172j0&sourceid=chrome&ie=UTF-8#q=bluetooth+chat+source
OR use bluetooth SPP from android market
Install and test by sending characters from the send message to test for connectivity .
Subsequently you can read through the example and get a feel of using the bluetooth api .
You can do so by using bluetoth spp from android market or google bluetooth sample code (bluetoothchat) to test whether e issues is with android code or arduino.

Categories

Resources