android how to get the name of connected bluetooth device [duplicate] - android

This question already has an answer here:
Android: How to find out name of the bluetooth device connected?
(1 answer)
Closed 6 years ago.
i want to know how to get the name of the connected bluetooth device in android
here is the code
NetworkInfo bluetooth = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_BLUETOOTH);
if(bluetooth.isConnected())
{
Toast.makeText(myprofile3Context,"bluetooth is connected", Toast.LENGTH_SHORT).show();
}
here i check if bluetooth device is connected or not. if bluetooth is connected i want know how to get the name of connected device.

try this
public String getLocalBluetoothName(){
if(mBluetoothAdapter == null){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
String name = mBluetoothAdapter.getName();
if(name == null){
System.out.println("Name is null!");
name = mBluetoothAdapter.getAddress();
}
return name;
}

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_ACL_CONNECTED.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//you can get name by device.getName()
} else if (BluetoothAdapter.ACL_DISCONNECTED
.equals(action)) {
}
}
};
Use extends BroadcastReceiver and add permissions in manifest

Related

Is it possible to filter Bluetooth Scan results to show devices with specific names

my app scans for Bluetooth devices, I only want it to show devices with a specific name (limiting the results viewed by the user). Not entirely sure if this can be achieved? Please see screenshots below
Current Bluetooth scan result:
Desired result:
Yes, you can filter it out.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
//
// use try-catch to keep tying on the logic -- John Melody added
try {
if (deviceName.contains("somethingsomething")) {
System.out.println(String.format("Ok %s", deviceName));
}
} catch(Exception e) {
e.printStackTrace();
}
//
}
}
};
Checkout[this][1] link
[1] : https: //developer.android.com/guide/topics/connectivity/bluetooth#FindingDevices

Classic Bluetooth discovery does not give me details other than MAC Address

I need to integrate Bluetooth Classic discovery and create connection between phone and device,but Discovering device does not gives more details in Receiver.My Code is:
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBluetoothAdapter = bluetoothManager.getAdapter();
}else {
mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
}
mBluetoothAdapter.startDiscovery();
public static class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Gson gson=new Gson();
LogUtils.errorLog("BC ","##: "+gson.toJsonTree(device));
//callback.onDeviceFound(device);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {
context.unregisterReceiver(this);
// callback.onDiscoveryFinished();
}
}
}
The code says it has the BluetoothDevice instance of the device that is recently discovered. Now following the developer guide BluetoothDevice we can find out this class has many information, which can be requested using it's methods.
For example:
device.getAddress(), to get the machine address of the device.
device.getName(), to get the local name of the device.
important thing about Bluetooth is mac address. once you get mac address,
1. you can pair, connect send and receive data
Example:
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress);
device.getName();
mSocket.connect(createRfcomSecureConnection);

Android Connect Bluetooth device automatically after pairing programmatically

In my app I need pairing bluetooth device and immediately connect with it.
I have the following function in order to pairing devices:
public boolean createBond(BluetoothDevice btDevice)
{
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = btDevice.getClass().getMethod("createBond", (Class[]) null);
Boolean returnValue = (Boolean) m.invoke(btDevice, (Object[]) null);
Log.d("pairDevice()", "Pairing finished.");
return returnValue;
} catch (Exception e) {
Log.e("pairDevice()", e.getMessage());
}
return false;
}
And I use it as the following way:
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//Connect with device
}
}
And it show me the dialog to pairing devices and enter the pin.
The problem is that createBond functions always return true, and it doen's wait until I enter the pin and paired with device, so I don't use correctly:
isBonded = createBond(bdDevice);
if(isBonded) {...}
So the question is How can I paired with device and when it is paired connect to it?
P.D My code is based in the first answer of the following thread: Android + Pair devices via bluetooth programmatically
I found the solution.
First I need a BroadcastReceiver like:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
// CONNECT
}
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Discover new device
}
}
};
And then I need register the receiver as follow:
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
context.registerReceiver(myReceiver, intentFilter);
In this way the receiver is listening for ACTION_FOUND (Discover new device) and ACTION_BOND_STATE_CHANGED (Device change its bond state), then I check if the new state is BOND_BOUNDED and if it is I connect with device.
Now when I call createBond Method (described in the question) and enter the pin, ACTION_BOND_STATE_CHANGED will fire and device.getBondState() == BluetoothDevice.BOND_BONDED will be True and it will connect.

Detect when bluetooth device disappears on Android

I'm creating a simple application that will communicate via Bluetooth. I have already created a simple Activity that lists the nearby devices with bluetooth turned on but unfortunately I can't figure out how could I detect when some devices disappear from the bluetooth network (bt gets turned off) so that I could remove that item from the list.
This is my code I wrote to add nearby BT devices to a ListView:
mNewDevicesArrayAdapter = new BluetoothDeviceArrayAdapter(this, 0, new ArrayList<BluetoothDevice>());
lvDiscovered = (ListView)findViewById(R.id.bt_dev_discovered_list);
lvDiscovered.setAdapter(mNewDevicesArrayAdapter);
...
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device);
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// TODO show no devices found!
}
}
};
I found no applicable ACTION intent of the case when a device gets disappeared. Maybe ACTION_DISCOVERY_FINISHED could be used, but how?
Thanks in advance!
I found an easy way to remove those devices from the list that was previously discovered.
Extending my code above I introduced an update list where I'm storing the newly discovered devices. When ACTION_DISCOVERY_FINISHED appears I'll update the ListView with this update list.
...
private ArrayList<BluetoothDevice> btDevicesUpdateList;
...
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
// in the paired devices list
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
if(mNewDevicesArrayAdapter.getCount() == 0){
// if the list is empty we add the device immediately to it
mNewDevicesArrayAdapter.add(device);
}
btDevicesUpdateList.add(device);
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mNewDevicesArrayAdapter.setItems(btDevicesUpdateList);
btDevicesUpdateList.clear();
mBtAdapter.startDiscovery();
}
}
}
// BluetoothDeviceArrayAdapter.java
public void setItems(ArrayList<BluetoothDevice> items){
this.items.clear();
this.items.addAll(items);
}
Devices that are unavailable will not be in the list.

How can I programmatically tell if a Bluetooth device is connected?

I understand how to get a list of paired devices, but how can I tell if they are connected?
It must be possible since I see them listed in my phone's Bluetooth device list and it states their connection status.
Add the Bluetooth permission to your AndroidManifest,
<uses-permission android:name="android.permission.BLUETOOTH" />
Then use intent filters to listen to the ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED, and ACTION_ACL_DISCONNECTED broadcasts:
public void onCreate() {
...
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter);
}
//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_FOUND.equals(action)) {
... //Device found
}
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
... //Device is now connected
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
... //Done searching
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
... //Device is about to disconnect
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
... //Device has disconnected
}
}
};
A few notes:
There is no way to retrieve a list of connected devices at application startup. The Bluetooth API does not allow you to query, instead it allows you to listen to changes.
A hoaky workaround to the above problem would be to retrieve the list of all known/paired devices... then trying to connect to each one (to determine if you're connected).
Alternatively, you could have a background service watch the Bluetooth API and write the device states to disk for your application to use at a later date.
In my use case I only wanted to see if a Bluetooth headset is connected for a VoIP app. The following solution worked for me.
Kotlin:
fun isBluetoothHeadsetConnected(): Boolean {
val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
return (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled
&& mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED)
}
Java:
public static boolean isBluetoothHeadsetConnected() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
&& mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
}
Of course you'll need the Bluetooth permission:
<uses-permission android:name="android.permission.BLUETOOTH" />
There is an isConnected function in the BluetoothDevice system API in https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java.
If you want to know if a bounded (paired) device is currently connected or not, the following function works fine for me:
public static boolean isConnected(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("isConnected", (Class[]) null);
boolean connected = (boolean) m.invoke(device, (Object[]) null);
return connected;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
For some reason, BluetoothAdapter.ACTION_ACL_CONNECTED could not be resolved by Android Studio. Perhaps it was deprecated in Android 4.2.2?
Here is a modification of Skylarsutton's code (Big thanks to Skylarsutton for his answer.) . The registration code is the same; the receiver code differs slightly. I use this in a service which updates a Bluetooth-connected flag that other parts of the app reference.
public void onCreate() {
//...
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(BTReceiver, filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
}
//else if...
}
};
This code is for the headset profiles, and probably it will work for other profiles too.
First you need to provide a profile listener (Kotlin code):
private val mProfileListener = object : BluetoothProfile.ServiceListener {
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
if (profile == BluetoothProfile.HEADSET)
mBluetoothHeadset = proxy as BluetoothHeadset
}
override fun onServiceDisconnected(profile: Int) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null
}
}
}
Then while checking Bluetooth:
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}
It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:
mBluetoothHeadset!!.connectedDevices
BluetoothAdapter.getDefaultAdapter().isEnabled ->
returns true when Bluetooth is open.
val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager
audioManager.isBluetoothScoOn ->
returns true when a device connected
I was really looking for a way to fetch the connection status of a device, not listen to connection events. Here's what worked for me:
BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bm.getConnectedDevices(BluetoothProfile.GATT);
int status = -1;
for (BluetoothDevice device : devices) {
status = bm.getConnectionState(device, BLuetoothGatt.GATT);
// compare status to:
// BluetoothProfile.STATE_CONNECTED
// BluetoothProfile.STATE_CONNECTING
// BluetoothProfile.STATE_DISCONNECTED
// BluetoothProfile.STATE_DISCONNECTING
}

Categories

Resources