I have created a BroadcastReceiver for BluetoothDevice.ACTION_FOUND in a Service to scan and Log the Bluetooth Device available. Part of this Service is to keep on checking every 30 seconds if the any of the previously found bluetooth devices is still available or not. Currently it throws me an error for Leaked IntendReceiver, I can fix that error, however I am just not convinced this is the right way to do this.
I am creating a new thread to handle bluetooth scanning, creating a while loop which runs every 30 seconds and inside that loop registering the BroadcastReceiver, putting thread on sleep, by the time sleep time is over the onReceive gives me results of the current scan, then I unregister BroadcastReceiver and repeat the loop.
I am unregistering the BroadcastReceiver after every single completion of while loop because the next scan gives me list of currently available devices and then I compare that with previous scan's data.
It is fulfilling my requirement however I have a strong feeling that its not the correct design. Could you please advice me on an alternate approach? Thanks..
Below is the relevant code from the Service-
class ScanBT extends Thread
{
static final long DELAYBT = 30000;
#Override
public void run()
{
isBTRunning = true;
Looper.prepare();
BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
try {
Log.d(TAG, "BT Scanning started");
while(isBTRunning)
{
if (!mBluetoothAdapter.isEnabled())
{
mBluetoothAdapter.enable();
Thread.sleep(15000);
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
Log.d(TAG,"Inside while loop for BT");
Thread.sleep(DELAYBT);
unregisterReceiver(mReceiver);
}
Looper.loop();
}
catch (InterruptedException e) {
Log.d(TAG, "BT Scanning stopped");
Looper.myLooper().quit();
}
}
}
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);
BTDevice = device.getName();
BTAddress = device.getAddress();
Log.d(TAG,"BT Found name: " + BTDevice);
Log.d(TAG,"BT Found address: " + BTAddress);
//Code to compare with previous scan results
}
}
};
Figured it out. There is no other way to achieve this. To keep the performance under control, I am now registering the receiver only once and then starting the discovery inside a loop with a sleep interval of 60 seconds.
Related
I would like the device names to show up in the textView of my app when they are found during scanning but nothing shows up.
I see the bluetooth is successfully enabled and my other device is visible but nothing ever shows up.
bluetoothAdapter = (BluetoothAdapter.getDefaultAdapter());
bluetoothAdapter.enable();
bluetoothAdapter.startDiscovery();
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
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
textView.append(device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
I know the above code was kinda intended for use in a listView but would it not still work in textView?
I think i have found the problem here.
What's happening is there is a problem when you call bluetoothAdapter.startDiscovery(); right after bluetoothAdapter.enable();
The adapter apparently needs a few seconds to get everything set up before you start doing stuff with it.
So i put a little delay in between those like so:
bluetoothAdapter.enable();
try {
Thread.sleep(3000);//3 seconds
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
bluetoothAdapter.startDiscovery();
And now everything seems to work.
Hi this is my first time posting.
Im making an android application that only discover Bluetooth device by using the friendly name and the mac address . Not pairing.
The problem im facing is my device fail to detect new device that enter the range after is start the scan about 10 to 12 second.
final BroadcastReceiver bReceiver = 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 the MAC address of the object to the arrayAdapter
// System.out.println(device.getAddress());
for(int i=0;i<listmac.size();i++)
{
if(listmac.get(i).equals(device.getAddress())){
System.out.println(listname.get(i));
myListView.setItemChecked(i, true);
}
}
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
isBreceiverRegisted = true;
}
}
public void off(){
myBluetoothAdapter.disable();
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
Sorry for my broke english
Simply because the discovery task has a timeout to prevent endless searched.
To be able to detect that discovery ended you need add this intent
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// When discovery is finished , start discovery again
myBluetoothAdapter.startDiscovery();
}
}
Be very careful in general about accidentally leaving your device in discovery-mode. Performing device discovery is a heavy procedure for the Bluetooth adapter and will consume a lot of its resources.
I have a bluetooth device.
If:
They have already paired and connected to the device
it becomes unplugged
then it becomes plugged back in
I would like to auto-connect to it. That's why I'm listening to ACTION_FOUND.
My code is fairly simple. The ACTION_BOND_STATE_CHANGED and ACTION_ACL_DISCONNECTED work just fine. I am completely unable to get the ACTION_FOUND to catch though. My "INTENT RECEIVED" log message never prints…
I feel like I am missing something simple. Thanks!
public void registerReceiver() {
if (BuildConfig.DEBUG) Log.e(TAG, "REGISTERING RECEIVER");
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
mainActivity.registerReceiver(receiver, filter);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BuildConfig.DEBUG) Log.e(TAG, "INTENT RECEIVED: " + String.valueOf(action));
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// … some stuff …
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
autoConnectDevice();
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
disconnectDevice();
}
}
};
public void unregisterReceiver() {
if (BuildConfig.DEBUG) Log.e(TAG, "UNREGISTERING RECEIVER");
mainActivity.unregisterReceiver(receiver);
}
I believe the ACTION_FOUND event only fires when you are running device discovery with the intent to pair your device to another. It would not fire when an already paired device comes back into range. Unfortunately, there does not appear to be an event for the case that you want.
Your best bet will be to start an AsycTask or Thread when the connection is lost and try to reconnect until successful or until you hit an arbitrary time limit and give up.
I'm working on an app that searches for discoverable devices and displays them as buttons.
When calling startDiscovery() I would say it works 30% of the time, based on the way I'm currently debugging it, with the BroadcastReceiver and ACTION_DISCOVERY_FINISHED.
I'm also using isDiscovering() to test if the startDiscovery() function is called but it returns false.
Is there a way to know if startDiscovery() is called successfully? And can you identify something in my code that would make it not fail?
Obs.: I have both BLUETOOTH AND BLUETOOTH_ADMIN permissions.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String Address;
// 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);
Address = device.getAddress();
System.out.println("Found Address: " + Address ); //DEBUG
//Do something with Address
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
System.out.println("Discovery finished");
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
MainActivity.mBluetoothAdapter.startDiscovery();
if (MainActivity.mBluetoothAdapter.isDiscovering()) {
System.out.println("Discovering..."); //DEBUG
}
}
Although I have a few discoverable devices available, none of them trigger onReceive() with ACTION_FOUND
UPDATE: I went to "Scan" under Bluetooth Settings while the app was running and I could not scan for new devices. I disabled/enabled Bluetooth and returned to the app and the problem was resolved. I don't know if that indicates that the adapter is busy or halted somehow.
I confirm this issue.
On some telephones you just need to disable/active BT. You can doit programatically with
mBluetoothAdapter.disable();
mBluetoothAdapter.enable();
On some telephones its not enough ( Samsung S5 ). To detect it, I use timer, and if on end of timeout the change of BT broadcast state (BluetoothAdapter.ACTION_DISCOVERY_STARTED or BluetoothAdapter.ACTION_DISCOVERY_FINISHED ) wasnt received => its sign that BT is not working. Actually I show dialog which propose to user reboot the telephone.
In android how can my Activity will get to know if a Bluetooth A2DP device is connected to my device.
Is there any broadcast receiver for that?
How to write this broadcast receiver?
Starting from API 11 (Android 3.0) you can use BluetoothAdapter to discover devices connected to a specific bluetooth profile. I used the code below to discover a device by its name:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
boolean deviceConnected = false;
BluetoothA2dp btA2dp = (BluetoothA2dp) proxy;
List<BluetoothDevice> a2dpConnectedDevices = btA2dp.getConnectedDevices();
if (a2dpConnectedDevices.size() != 0) {
for (BluetoothDevice device : a2dpConnectedDevices) {
if (device.getName().contains("DEVICE_NAME")) {
deviceConnected = true;
}
}
}
if (!deviceConnected) {
Toast.makeText(getActivity(), "DEVICE NOT CONNECTED", Toast.LENGTH_SHORT).show();
}
mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, btA2dp);
}
}
public void onServiceDisconnected(int profile) {
// TODO
}
};
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.A2DP);
You can do that for every bluetooth profile. Take a look at Working with profiles in Android's guide.
However, as written in other answers, you can register a BroadcastReceiver to listen to connection events (like when you're working on android < 3.0).
You cannot get the list of connected devices by calling any API.
You need instead to listen to the intents ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECTED that notifies about devices being connected or disconnected.
No way to get the initial list of connected devices.
I had this problem in my app and the way I handle it (didn't find better...) is to bounce off/on the Bluetooth at application start to be sure to start with an empty list of connected devices, and then listen to the above intents.
muslidrikk's answer is broadly correct; however you can alternatively use fetchUUIDsWithSDP() and see what you get back... it's a bit of a hack though -- you'd have to know what UUIDs (capabilities) you could expect from the device, if it were turned on. And that might be difficult to guarantee.
For BluetoothHeadset specifically, you can call getConnectedDevices() to get connected devices for this specific profile.
Reference: http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html
Other cases you need to register a receiver for that.
In your activity, define broadcast receiver...
// 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