I am working on Bluetooth related application where I provide user a list of nearby Bluetooth devices and also I provide a rescan button to restart scanning process. When user comes to this view application start discovery process and if application founds device it get display in a list. But if the user presses rescan button, first application clear list and then restart scanning process then application fails to list same device again.
I don't know why application fails to rescan same device again.
Check out code below :
Starting search
mBluetoothAdapter.startDiscovery();
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
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
The Discovery procedure is in some sense a probabilistic, so if you can't get identical lists in two sequential calls it is ok. I'd rather wonder are you able to enumerate any other BT-devices during subsequent calls. And if answer is always 'yes', and you experience problems with that only device, check if it is operating correctly. If after first successful call you can't enumerate the devices - either your code is incorrect or your device you're using for debugging works not very well (that's happens quite often in the Android World).
Related
I have two Android phones. I want to make an auto connection between them via Bluetooth. For example,
I have my android phone which paired to another Bluetooth. When I put these phone near together, they need to detect Bluetooth device, and automatically connect to a selected android phone (known Adress/MAC/Paired before). I don't need to connect it again. I want this kind of connectivity in my Android application.
I google and found some related reference, but they are did not solve the issue yet. I think that I need to create a thread/service to automatically connect Bluetooth when they are in range. However, I can not implement it. If you have a good solution, please let me know. Thank you
Automatically connect to paired bluetooth device when in range
Find already paired bluetooth devices automatically, when they are in range
/**
* 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();
// 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 it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
These broadcast receivers will fire only after the discovery process runs.
Discovery can be started in two ways: either manually in Bluetooth settings, or programatically by calling BluetoothAdapter#startDiscovery(). However, the documentation states that:
Device discovery is a heavyweight procedure. New connections to remote Bluetooth devices should not be attempted while discovery is in progress, and existing connections will experience limited bandwidth and high latency. Use cancelDiscovery() to cancel an ongoing discovery. Discovery is not managed by the Activity, but is run as a system service, so an application should always call cancelDiscovery() even if it did not directly request a discovery, just to be sure.
This implies that discovery should be done as a one-off procedure, not continuously running in the background—apart from slowing down other Bluetooth connections, it will drain the battery quickly.
I would like to create a bluetooth app.. when I click the app it will show a dialogue box asking for permission to turn on bluetooth and scan for devices.
I am very new to android programming and I dont know java language.I just learn by watching youtube videos.I need to learn for my school project.I have learned how to make dialogue boxes and button using eclipse but I'm not sure how to turn on bluetooth and scan for device instantaneously when I open the app.I found that there are tutorials on bluetooth where the user have to press buttons so that the bluetooth will turn on and scan on press of button.
Someone please help me.
Thank you
You can enable the bluetooth as follows..
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
And see this link to search for devices in range..
One answer in that link says..
To start search
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
To find 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
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
To start all these functions whenever the app is launched just put these codes inside onCreate()
Try it...
I would suggest to do a little bit more research on that because your question is quite basic and simple to sort out.
Start checking Android's Bluetooth reference and here you will find exactly what you need.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
Moreover, on the right side of the guide you have a couple of links to Bluetooth example projects. As I said, start checking it and try to write you app, you will find it very easy and simple.
I'm working on a personal electronics project and I would like to create an app to log GPS data in addition to several other things.
The project is an automatic bicycle derailleur (it will shift gears automatically based on a number of factors such as speed, pedal cadence, gyroscope angle, etc). In addition I would like to create an app which will log things like speed, routes taken, number of hours ridden, etc. To save money, I would like to use my Android phone as both a screen for displaying some of these vitals as well as logging data with the GPS.
I'm very new to Android development, but my question is this: Would it be possible to tell the phone to automatically begin logging data (and possibly open the app, depending on what I decide) once it has been connected to the bike via bluetooth? And concurrently, I'd like it to stop and close the app once it's been disconnected.
Thanks
The problem as I see it, is how you plan on connecting to the bike's Bluetooth radio. Typically an application will initiate a Bluetooth connection (which is different from pairing.) Running a service in the background looking for your Bluetooth device and connecting typically wouldn't be a good solution because searching for Bluetooth devices is very resource intensive.
You might be better off just having the connection initiate when the user starts the app.
The second part, to stop the app once the connection is dropped (becomes out of range, or the device on the bike drops the connection,) is quite straight forward. Make a broadcast receiver:
public class DisconnectBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(BasicDMMView.this, "Device disconnected!", Toast.LENGTH_SHORT).show();
// Close anything you need to (log files etc.)
finish();
}
}
And then register the receiver once you've opened the bt connection:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
mReceiver = new DisconnectBroadcastReceiver();
registerReceiver(mReceiver, filter);
And don't forget to unregister the receiver when you leave the Activity:
unregisterReceiver(mReceiver);
Everywhere I look I find this method "getBondedDevices()" for my bluetooth adapter. However, I have my tablet and another bluetooth device sitting next to me, and I can't figure out how to actually get the device to show up on the list of bonded devices.
In Bluetooth terms, "bonded" and "paired" are basically synonyms (officially, the process of pairing leads to a bond, but most people use them interchangeable). In order for your device to be added to that list, you must go through the process of Discovery, which is how one device searches and finds another, and then Pair the two together.
You can actually do this from the device settings as a user, but if you are looking to so so within the context of an app, your process will likely look something like this:
Register a BroadcastReceiver for BluetoothDevice.ACTION_FOUND and BluetoothAdapter. ACTION_DISCOVERY_FINISHED
Start discovery by calling BluetoothAdapter.startDiscovery()
Your receiver will get called with the first action every time a new device is found in range, and you can inspect it to see if it's the one you want to connect with. You can call BluetoothAdapter.cancelDiscovery() once you've found it to not waste the battery any more than necessary.
When discovery is complete, if you haven't canceled it, your receiver will get called with the second action; so you know not to expect any more devices.
With a device instance in hand, open a BluetoothSocket and connect(). If the devices are not already bonded, this will initiate pairing and may show some system UI for a PIN code.
Once paired, your device will show up in the bonded devices list until the user goes into settings and removes it.
The connect() method also actually opens the socket link, and when it returns without throwing an exception the two devices are connected.
Now connected, you can call getInputStream() and getOutputStream() from the socket to read and write data.
Basically, you can inspect the list of bonded devices to quickly get access to an external device, but in most applications you will be doing a combination of this and true discovery to make sure you can always connect to the remote device regardless of what the user does. If a device is already bonded, you'd just be doing steps 5-7 to connect and communicate.
For more information and sample code, check out the "Discovering Devices" and "Connecting Devices" sections of the Android SDK Bluetooth Guide.
HTH
API level 19 and above you can call createBond() on BluetoothDevice instace to which you want to connect.
You will require some permissions to discover and list the visible devices
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Code to discover and list the devices:
bluetoothFilter.addAction(BluetoothDevice.ACTION_FOUND);
bluetoothFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
bluetoothFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(bluetoothReceiver, bluetoothFilter);
private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_FOUND");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devicesList.add((device.getName() != null ? device.getName() : device.getAddress()));
bluetoothDevicesAdapter.notifyDataSetChanged();
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_DISCOVERY_STARTED");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_DISCOVERY_FINISHED");
getActivity().unregisterReceiver(bluetoothReceiver);
}
}
};
Just call createBond() on selected device.
Is it possible to create a service that can listen for devices nearby and log device info to a file?
Yes, your service can listen for new Bluetooth devices, as described by Vipul Shah, but the real issue is how do you cause your device to find other Bluetooth devices in the first place.
ACTION_FOUND is sent when a remote device is found during discovery. You can call BluetoothAdapter.startDiscovery() to start the discovery process, but the problem is that very few devices are normally discoverable. A couple of years ago it was common for devices to remain discoverable all the time, but now the user is expected to make a device temporarily discoverable as needed to pair it.
So, it doesn't make sense to have a service that periodically does discovery (and listen for ACTION_FOUND) both because it consumes a lot of battery and because you won't find anything.
If you know the Bluetooth address of the devices that you are looking for then you could try to connect to them, but I assume that is not the case.
Yes it is very much possible
Step 1 You will need to create one service
Step 2 You will need BluetoothDevice.ACTION_FOUND Broadcast Receiver to look for nearby devices.
Step 3 Then you can query all found devices one by one.
Step 4 As you will fast enumerate over found devices dump their information inside file.
Below is broadcast Receiver
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
// You will log this information into file.
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
Register the broadcast receiver for intent action as follows
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
Hope this helps.