How to get the connected BT device Address in Android - android

In my mobile app i have to get the connected BT address and start SPP connection. Is there any way to get the connected BT device address?

Following may be help you
public void getDeviceList(){
BluetoothAdapter mBlurAdapter= BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBlurAdapter.getBondedDevices();
if (pairedDevices.isEmpty()) {
Log.e("DeviceActivity ",
"Device not founds");
return ;
}
for (BluetoothDevice devices : pairedDevices) {
Log.d("DeviceActivity", "Device : address : " + devices.getAddress() + " name :"
+ devices.getName());
}
}
Also don't miss to define permission

Related

BluetoothManager getConenctedDevices returns an empty array

I've connected to Xiaomi air buds via bluetooth settings on my phone.
Then, I tried to use getConnectedDevices(BluetoothProfile.GATT_SERVER) and getConnectedDevices(BluetoothProfile.GATT) methods to get a list of connected devices, but in both cases I got an empty array as a result. If I try to use some other profile in getConnectedDevices() I get an exception that says that I'm using a wrong profile.
How can I correctly get a list of currently connected bluetooth devices to my phone.
code example, in onCreate:
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> connectedDevices = mBluetoothManager.getConnectedDevices(BluetoothProfile.GATT_SERVER);
for (BluetoothDevice b :
connectedDevices) {
Log.e(TAG, "onStart: connectedDevice - " + b.toString() );
}
To get a list devices that you connected to ( in the past )
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedList = btAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedList )
{
Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());
}
To get the device you correctly connected to you will have to use a broadcast receiver like in the following
private final BroadcastReceiver btReceiver = 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)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("Device",device.getName()+ "\n"+ device.getAddress()+"\n"+ device.getBondState());
}
}
};
There's a few more ways to just find out what the state of the connection of the headset as shown here.
if that still not answering your question then I'm sorry I probably misunderstood your question / need.

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

How to get name of the connected Bluetooth device on android

I'm trying to get the name of the device that is connected to the Android phone running android Oreo.
I was searching for an answer for the past two days, and none of them worked. suggestions mostly returning ioexception-read-failed-socket-might-closed-bluetooth error
The question is, is there any way to make Query that returns the connected Bluetooth device?
These are the links and suggestion which not working:
IOException: read failed, socket might closed - Bluetooth on Android 4.3
In Android, how to get the profile of a connected bluetooth device?
list connected bluetooth devices?
I can get information about the device that is previously paired and trying to make a connection or a device trying to pair to the device. what I want is the name or the connection state of the currently paired and connected device.
here is the answer :
String name;
String address;
String threadName;
public void checkConnected()
{
BluetoothAdapter.getDefaultAdapter().getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET);
}
private BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener()
{
#Override
public void onServiceDisconnected(int profile)
{
}
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy)
{
for (BluetoothDevice device : proxy.getConnectedDevices())
{
name = device.getName();
address = device.getAddress();
threadName = Thread.currentThread().getName();
Toast.makeText(MainActivity.this, name+" " + address+ threadName, Toast.LENGTH_SHORT).show();
txtName.setText(name + " " + address);
Log.i("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = "
+ BluetoothProfile.STATE_CONNECTED + ")");
}
BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy);
}
};
Have you tried this?
BluetoothServerSocket bluetoothServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord("abc", uuid);
BluetoothSocket bluetoothSocket = bluetoothServerSocket.accept();
BluetoothDevice device = bluetoothSocket.getRemoteDevice();
String deviceName = device.getName();

Android bluetooth get device name

I have multiple Bluetooth devices from a vendor. When I paired my device it takes the same friendly name say "BTDevice". Now when i pair all multiple devices I get the same name. in my ListView. I cannot show the the address of the device in my List.I tried renaming the friendly name in Bluetooth settings but it still shows me "BTDevice" as device name when I do device.getName() any suggestions to overcome this issue.
Here is the code.
private void getDevice(){
ArrayList<String> bondedAdapter = new ArrayList<String>();
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedSet = bluetoothAdapter.getBondedDevices();
int count = 0;
if(bondedSet.size() > 0){
for(BluetoothDevice device : bondedSet){
bondedAdapter.add(device.getName()+"\n"+device.getAddress());
Log.i("TabInflater", device.getName());
}
}else{
bondedAdapter.add("No Devices");
}
} catch (Exception e) {
Log.e("TabInflater","Error");
}
}
In my log it says I have paired to (Addresses hidden intentionally)
BTDevice
BTDevice
BTDevice

Monitoring the connection of a paired bluetooth device

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

Categories

Resources