Find all Bluetooth Devices within range of the phone - android

I know that I can discover new devices with BluetoothAdapter.startDiscovery()
IntentFilter(BluetoothDevice.ACTION_FOUND) and BroadcastReceiver.
And get all paired Bluetooth Devices via BluetoothAdapter.getBondedDevices().
But if I pair a device I don't know if it's reachable or not.
Is there a way to get all devices within a reach of phone? I don't even need BluetoothDevice Objects, I won't connect with them, I just want their addresses.

You can exclude the bonded devices from the array/list of the devices found.
Something like this:
if (device.bondState != BluetoothDevice.BOND_BONDED) {
mDevicesArrayAdapter.add(device.name + "\n" + device.address)
}

Related

Android paired Bluetooth disappears when device reboots

I want the connected device to get BluetoothDevice device information without scanning Bluetooth, so I store all Bluetooth-connected devices.
However, while other devices behave as expected, one type of Bluetooth devices will lose their paired information when the phone is rebooted.
Do anyone know why this may happen or have an alternative way to obtain Bluetooth Device information without scanning?
You can use BluetoothAdapter.
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mac);
device.connectGatt(mContext, false, mGattCallback);
// TODO your code
If the bluetooth device is not around, in BluetoothGattCallback's onConnectionStateChange will report BluetoothGatt.STATE_DISCONNECTED.
BluetoothDevice's creator has packages scope. But the source code of BluetoothAdapter's getRemoteDevice is:
public BluetoothDevice getRemoteDevice(String address) {
return new BluetoothDevice(address);
}

Bluetooth scan results increase with manual scan in Android

I have implemented a broadcast receiver in Android to listen to all available Bluetooth signals. The receiver works, but only shows four devices. When I manually scan for devices in the android menu, I suddenly see eight different devices in my app.
How can I see all available devices without using manual scan?
code:
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);
// Add the name and address to an array adapter to show in a ListView
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
Log.d("bluetoothSignal", "name: "+ device.getName() + " adress: "+ device.getAddress() + "strength: "+ rssi + " Data: " + intent.getData());
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
Be aware that in the 'android menu' scanning results can show the paired devices, as well as scanned devices. So this could account for the duplicates. This case however is not very likely because any good Bluetooth scanning results should prevent duplicate results but there may be special cases where duplicates could be allowed.
What I suspect is actually occurring is that the system settings is returning tradition Bluetooth Devices (using rfcomm) and Bluetooth LE devices. The problem is, most Bluetooth device menus don't show a identifier that indicates whether a device is tradition or Bluetooth LE device, just the device name. Furthermore, when using BluetoothAdapter.startDiscovery() it tends to prefer traditional Bluetooth Devices and only occasionally returns Bluetooth LE devices. For example in my experience, 85 percent of the time it does not discover Bluetooth LE devices in the time it takes to to complete a discovery process, 13 seconds. I recommend using a use both the traditional scanning mechanism and the Bluetooth LE scanning mechanism. To perform a Bluetooth LE scan get a reference to the BluetoothLeScanner get calling BluetoothAdapter.getBluetoothLeScanner(). Once you have a reference, call BluetoothLeScanner.startScan(ScanCallback callback). The ScanCallback will get fired with discovered Bluetooth LE devices that you can add to your ListView's adapter. Try this and see if you get similar results with the 'android menu'.

Android bluetooth scan of already paired

I'm making an Android application that scan all device in the room and connect/pair to the device automatically or not, depending on the name prefix.
I tried some examples and the scan result return only unpaired devices. So I need that the result of the scan return also already paired devices. Is it possible on Android ? (I already done this on windows)
Yes. You need to get the local bluetooth adapter
Adapter = BluetoothAdapter.getDefaultAdapter();
get paired devices into a private set Bluetooth device
devicepair = Adapter.getBondedDevices();
And then from that point it should be a simple for loop to add device pair to a list view that shows your bluetooth devices
for(BluetoothDevice : devicepair)
//your array name or whatever inside the for loop
listviewarray.add(devicepair.getName());

Connect to specific Bluetooth device with a click

I'm trying to connect to a specific device using my Android APP, until now what I was able to do is get the paired items doing this :
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set < BluetoothDevice > pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device: pairedDevices) {
mDeviceName.add(device.getName());
mDeviceMAC.add(device.getAddress());
}
}
bluetoothClass.setDeviceName(mDeviceName);
bluetoothClass.setDeviceMac(mDeviceMAC);
Where I get the MAC and the Device name of all of my paired devices. The thing that I would like to do is when I select one it connects to the Bluetooth device.
EXAMPLE
On a Samsung S4 when I turn on the Bluetooth it popups a Dialog whitch contains all of my paired devices and when I click on anyone it connects (I've i'm able to ...) so basically I want to do this, since now I've been getting the paired devices (I don't know if it's the best way to get that but it does) and then when user click on anyone it connects to the device.
It's something like this question but it's unfortunately unanswered.
It's impossible to give you an example within this format, so I have provided you
with a good sample and helpful links to help you understand the sample.
I recommend you follow the steps I have provided and then, when you have
specific problems, you can bring it here, with the code snippet you are having
difficulty with.
I recommend you use download this sample code:
http://developer.android.com/samples/BluetoothChat/index.html
If you haven't already, it's good to study this:
http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html
This is a good tutorial and they have many tutorials:
http://www.tutorialspoint.com/android/android_bluetooth.htm
You will need the following permissions in your manifest:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
This is one intent that is advisable to use, to check to see if BT is enabled:
if (!mBluetoothAdapter.isEnabled()) {
android.content.Intent enableIntent = new android.content.Intent(
android.bluetooth.BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
and to make your device discoverable to other devices:
if (mBluetoothAdapter.getScanMode() !=
android.bluetooth.BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
android.content.Intent discoverableIntent =
new android.content.Intent(
android.bluetooth.BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
android.bluetooth.BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
300); // You are able to set how long it is discoverable.
startActivity(discoverableIntent);
}
As I mentioned in my answer here:
You can avoid using an intent to search for paired devices. When
connecting to a device that is not paired, a notification will pop up
asking to pair the devices. Once paired this message should not show
again for these devices, the connection should be automatic (according
to how you have written your program).
I use an intent to enable bluetooth, and to make my device
discoverable, I then set up my code to connect, and press a button to
connect. In your case, you will need to ensure your accessories are
discoverable also. In my case I use a unique UUID, and both devices
must recognise this to connect. This can only be used if you are
programming both devices, whether both are android or one android and
one other device type.
You will need to understand how to use sockets, this is how the devices communicate.
I recommend studying these two links:
http://developer.android.com/reference/android/bluetooth/BluetoothSocket.html
http://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html
Sockets are used to set up connections between devices. There will be a server socket and device sockets (determined by many factors, the programmer, the actual devices). The server socket listens for incoming connections, when a connection is accepted the devices connect, each with a simple socket.
I am not sure how much you know about threading.
The connection needs to be managed with threads:
http://developer.android.com/guide/components/processes-and-threads.html
http://android-developers.blogspot.com.au/2009/05/painless-threading.html
The connection between the devices is managed on threads separate from the User
Interface thread. This is to prevent the phone from locking up while it is
setting up, seeking and making a BT connection.
For instance:
AcceptThread - the thread that listens for a connection and accepts the connection (via the serversocket). This thread can run for an extended time waiting for a device to connect with.
ConnectThread - the thread that the device connecting to the server uses to connect to the serversocket.
ConnectedThread - this is the thread that manages the connection between both sockets.
Let me know if this helps you.

How to Connect to a device in android using WiFiP2p without discovering it

I want to connect my tablet to my phone using WiFi direct in order to send some data like pictures etc from my phone to tablet.
But I do not want my phone to discover it first i.e I don't wanted to use discoverPeers() method of WiFiP2pManger.
How can I achieve this goal?
In your phone, use createGroups(). This makes your phone become the groupOwner. Then call discoverPeers() in your tablet, it will find your phone without your phone calling discoverPeers().
In your phone:
wifiP2pManager = (WifiP2pManager) context.getSystemService(context.WIFI_P2P_SERVICE);
channel=wifiP2pManager.initialize(context,context.getMainLooper(),null);
wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.i(TAG,"Creating p2p group");
}
#Override
public void onFailure(int i) {
Log.i(TAG,"Creating group failed, error code:"+i);
}
});
In your tablet, discover peers, request peers and connect peers as normal
In order to establish a WiFi Direct connection both phones should be running WiFi Direct discovery. In other words, they will see each other when they are both scanning for WiFi direct connections at the same time. This is because the way WiFi Direct works is that when phones are scanning for WiFi Direct connections, they will negotiate with the other peers for the role of Access Point or Slave device. Hence both need to call discoverPeers() to become discoverable themselves and find nearby devices.
In your use case you could even build your application using wifi hotspot
This solution doesn't work. In Android both need to be on discovery mode in order to connect.

Categories

Resources