Android Application to Discover Nearby iPhone Devices - android

I am developing an Android Application where in I display the nearby iPhone devices. I have used the standard Android Bluetooth API's as well as Android Bluetooth LE API's for scanning the nearby iPhones. But I am unable to get the list of iPhones.
Note:
I see that the Settings Application present in the Stock Android is able to display all the devices.
Target Android OS - Marshmallow.
I am a newbie to Android. Kindly elaborate the answers for my better understanding. I have checked other links on Google and was not getting my desired result.
Standard Android Bluetooth Scan/discover(Scan and displays nearby devices but not an iPhone)
private void displayListOfFoundDevices(){
arrayOfFoundBTDevices = new ArrayList<BluetoothObject>();
// start looking for bluetooth devices
mBluetoothAdapter.startDiscovery();
// Discover new devices
// Create a BroadcastReceiver for ACTION_FOUND
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);
// Get the "RSSI" to get the signal strength as integer,
// but should be displayed in "dBm" units
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
// Create the device object and add it to the arrayList of devices
BluetoothObject bluetoothObject = new BluetoothObject();
bluetoothObject.setBluetooth_name(device.getName());
bluetoothObject.setBluetooth_address(device.getAddress());
bluetoothObject.setBluetooth_state(device.getBondState());
bluetoothObject.setBluetooth_type(device.getType()); // requires API 18 or higher
bluetoothObject.setBluetooth_uuids(device.getUuids());
bluetoothObject.setBluetooth_rssi(rssi);
arrayOfFoundBTDevices.add(bluetoothObject);
// 1. Pass context and data to the custom adapter
FoundBTDevicesAdapter adapter = new FoundBTDevicesAdapter(getApplicationContext(), arrayOfFoundBTDevices);
// 2. setListAdapter
setListAdapter(adapter);
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); }
BluetoothLE Code snippet(Scan and displays nearby devices but not an iPhone)
btManager =(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
btScanner = btAdapter.getBluetoothLeScanner();
if (btAdapter != null && !btAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}
// Make sure we have access coarse location enabled, if not, prompt the user to enable it
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect peripherals.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
// Device scan callback.
private ScanCallback leScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
Log.i("Main","Scan Result: Add: " +result.getDevice().getAddress());
peripheralTextView.append("Device Name: " + result.getDevice().getName()+ " add: " + result.getDevice().getAddress() + " rssi: " + result.getRssi() + "\n");
// auto scroll for text view
final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
}
};

Related

Android API to Connect to Wifi Network

I'm totaly lost in the versions of WiFi APIs.
I want to connect to a configured WiFi Network programmaticaly.
As decribed in this question:
Connect to wifi network Android programmatically
I develop on Android 10 and want to write a code that is also compatible with older Android Versions.
On my android 10 the code described does not work.
What code do I need to implement the functionality on Android 10?
What do I do to write an application that also runs on my other Android 9 phone?
Regards Jürgen
From Android Q, connecting to Wifi Network has changes a lot.
First of all the code you are using or #matdev mentioned uses API public int addNetwork (WifiConfiguration config) from WifiManager is deprecated in Android 10 and will return -1 as networkID.
From Android Q, two classes are suggested for Wifi connection. But each of them has its own advantage and disadvantage.
1. WifiNetworkSpecifier
A code example from WifiUtil Library
WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder()
.setSsid(scanResult.SSID)
.setBssid(MacAddress.fromString(scanResult.BSSID));
final String security = ConfigSecurities.getSecurity(scanResult);
ConfigSecurities.setupWifiNetworkSpecifierSecurities(wifiNetworkSpecifierBuilder, security, password);
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(wifiNetworkSpecifierBuilder.build())
.build();
// not sure, if this is needed
if (networkCallback != null) {
connectivityManager.unregisterNetworkCallback(networkCallback);
}
networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(#NonNull Network network) {
super.onAvailable(network);
wifiLog("AndroidQ+ connected to wifi ");
// bind so all api calls are performed over this new network
connectivityManager.bindProcessToNetwork(network);
}
#Override
public void onUnavailable() {
super.onUnavailable();
wifiLog("AndroidQ+ could not connect to wifi");
}
};
connectivityManager.requestNetwork(networkRequest, networkCallback);
My observation with this implementation is - It is more like P2P communication, and at this time other application from the same device cannot use internet from the connected WiFi network
2. WifiNetworkSuggestion
A code example from developer.android.com
final WifiNetworkSuggestion suggestion1 =
new WifiNetworkSuggestion.Builder()
.setSsid("test111111")
.setIsAppInteractionRequired(true) // Optional (Needs location permission)
.build();
final WifiNetworkSuggestion suggestion2 =
new WifiNetworkSuggestion.Builder()
.setSsid("test222222")
.setWpa2Passphrase("test123456")
.setIsAppInteractionRequired(true) // Optional (Needs location permission)
.build();
final WifiNetworkSuggestion suggestion3 =
new WifiNetworkSuggestion.Builder()
.setSsid("test333333")
.setWpa3Passphrase("test6789")
.setIsAppInteractionRequired(true) // Optional (Needs location permission)
.build();
final PasspointConfiguration passpointConfig = new PasspointConfiguration();
// configure passpointConfig to include a valid Passpoint configuration
final WifiNetworkSuggestion suggestion4 =
new WifiNetworkSuggestion.Builder()
.setPasspointConfig(passpointConfig)
.setIsAppInteractionRequired(true) // Optional (Needs location permission)
.build();
final List<WifiNetworkSuggestion> suggestionsList =
new ArrayList<WifiNetworkSuggestion> {{
add(suggestion1);
add(suggestion2);
add(suggestion3);
add(suggestion4);
}};
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final int status = wifiManager.addNetworkSuggestions(suggestionsList);
if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
// do error handling here…
}
// Optional (Wait for post connection broadcast to one of your suggestions)
final IntentFilter intentFilter =
new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);
final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(
WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
return;
}
// do post connect processing here...
}
};
context.registerReceiver(broadcastReceiver, intentFilter);
My observation with the above mentioned implementation is, when you call the wifiManager.addNetworkSuggestions it return success and show user a notification for connection. If the user accept, device gets connected to the WiFi network and other app can user internet. But if user disconnect from network and you call wifiManager.addNetworkSuggestions again, it will return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE error.
It looks like this API just provide a suggestion list of networks where the device can auto connect. But the connection will be determined by the OS.
But if you really need a solution, an undocumented way use to the Default Wifi QR Code Scanner from Android Source that can detect both QR Code schems Zxing and DPP.
here is an a code example :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_WIFI_QR_SCANNER && resultCode == RESULT_OK)
{
//WIFI Connection is Successful
}
else
{
//.......
}
}
#RequiresApi(api = Build.VERSION_CODES.Q)
private void startWifiQRCodeScanner(Context context)
{
final String INTENT_ACTION_WIFI_QR_SCANNER = "android.settings.WIFI_DPP_ENROLLEE_QR_CODE_SCANNER";
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isEasyConnectSupported())
{
final Intent intent = new Intent(INTENT_ACTION_WIFI_QR_SCANNER);
startActivityForResult(intent, REQUEST_CODE_WIFI_QR_SCANNER);
}
}
Here is a solution working from Android 6 (API level 23)
String AP_SSID = "YourWifiNetworkSSID";
String AP_PASSWORD = "YourWifiNetworkPassword";
wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + AP_SSID + "\""; // Please note the quotes. String should contain ssid in quotes
conf.preSharedKey = "\"" + AP_PASSWORD + "\"";
wifiManager.addNetwork(conf);
try {
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + AP_SSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
} catch (SecurityException e) {
Log.e(TAG, e.getMessage());
}

How to view list of devices that is connected to my router and select one of them then send and receive data from it

I am new to android application development and I want to build an application that uses wifi to connect to another devices (not mobile devices) and sends some data from my phone to a device and receives some data from the other device.
What I have in my local network:
mobile phone support wifi with android os.
device support wifi connection (e.g. temperature sensor).
What I need:
The phone needs to connect to the router and receive a list of available devices and check if the sensor is connected to the network or not.
Connect to the sensor and send a message from the phone that tells the sensor to measure the temperature.
The sensor sends back a message that contains the temperature.
Your question is nor quite clear to me. But as per my understanding you want to list down some Wi-Fi enabled devices on your mobile & then connect to one of them & finally communicate with them.
For Listing all access points you have to implement the code below.
private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context c, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
List<ScanResult> scanResults = mainWifiObj.getScanResults();
mScannedNetworksAdapter.clear();
listView_Access_point.clearChoices();
if (scanResults != null) {
for (ScanResult result : scanResults) {
mScannedNetworksAdapter.add(result)
}
}
listView_Access_point.setAdapter(mScannedNetworksAdapter);
}
}
};
Now After listing all the Wi-Fi access points you have to click one of them to get connected. To do this you have implement OnItemClickListener & then override onItemclick(). See the code below.
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
ScanResult result = (ScanResult) parent.getItemAtPosition(position);
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + result.SSID + "\"";
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
if(list!=null){
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + result.SSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
}
}
Then you have to implement a BroadcastReceiver which tells if the access point is connected successfully.
private final BroadcastReceiver mWifiConnectionEstablished = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
String action = intent.getAction();
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (NetworkInfo.State.CONNECTED.equals(nwInfo.getState()) && nwInfo.isConnected()) {
//The connection is established. Now do your stuff here
}
}
}
};
Finally there are several methods for communication. One of them is socket communication. You will get several examples in google for socket communication in android.

Android Bluetooth: fetchUuidsWithSdp() does not return all UUIDs on some devices

I have two different bluetooth apps. The first provides a service and listens to commands from the other commander app. I have a GT-I9100T phone and a GT-P5210 tablet. The tablet when acting at the listener works fine and the phone can see the UUID for my app. But when I run the phone as the listener, the UUID of the listener is not listed.
I filter the devices by my application UUID so that I know I am talking only to those devices with my application running.
My listening app looks like this (I get the same result if I use an insecure connection as well):
private final UUID GUID = UUID.fromString("3DEF793A-FA94-4478-AE56-108854B1EF4B");
// other stuff....
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(APP_NAME, GUID);
My commander app MainActivity looks likes this:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.i(TAG,"Action received: "+action);
if(action.equals(BluetoothDevice.ACTION_UUID)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(TAG,"Received uuids for "+btd.getName());
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
StringBuilder sb = new StringBuilder();
List<String> uuids = new ArrayList<String>(uuidExtra.length);
if(uuidExtra != null) {
for (int i = 0; i < uuidExtra.length; i++) {
sb.append(uuidExtra[i].toString()).append(',');
uuids.add(uuidExtra[i].toString());
}
}
Log.i(TAG,"ACTION_UUID received for "+btd.getName()+" uuids: "+sb.toString());
ListContent.addItemWithUUIDs(btd, uuids);
}
}
}
My list content (I am using the master/detail template):
public static synchronized void addItem(BluetoothItem item) {
BluetoothDevice btd = item.mBluetoothDevice;
Log.i(TAG,"Attempting to add "+item.mBluetoothDevice.getName());
if(ITEMS.contains(item)) {
Log.i(TAG,item.mBluetoothDevice.getName()+" already in list");
return;
}
// Do we know this device?
Parcelable[] uuids = btd.getUuids();
Set<String> setUUIDs = new HashSet<String>();
StringBuilder sb = new StringBuilder();
if(uuids != null) {
for (Parcelable parcelable : uuids) {
sb.append(parcelable.toString()).append(',');
setUUIDs.add(parcelable.toString());
}
}
Log.v(TAG,"Device has uuids: "+sb.toString());
if ((btd.getUuids() != null && setUUIDs.contains(BluetoothItem.GUID.toLowerCase()))){
Log.i(TAG, "Found app device: " + btd.getName());
addItem(btd);
} else {
// If we don't know this device, perform sdp fetch of uuids
Log.i(TAG,"Requesting fresh UUIDs for: "+btd.getName());
// this is flushed when discovering finishes
CANDIDATES.add(btd);
}
}
public static synchronized void addItemWithUUIDs(BluetoothDevice btd, List<String> uuids) {
Log.i(TAG,"Attempting to add with uuids"+btd.getName()+" uuids: "+btd.getUuids());
if (uuids.contains(BluetoothItem.GUID)) {
Log.i(TAG, "Found app device: " + btd.getName());
addItem(btd);
} else {
Log.i(TAG, "Ignoring device " + btd.getName() + " without app guid");
}
}
When discovery is finished, this happens:
for (BluetoothDevice i : ListContent.CANDIDATES) {
Log.i(TAG,"Fetching UUIDs for "+i.getName());
i.fetchUuidsWithSdp();
}
ListContent.CANDIDATES.clear();
The logcat output when using the tablet as the commander and phone as listener:
DeviceListActivity(29524): Received uuids for GT-I9100T
DeviceListActivity(29524): ACTION_UUID received for GT-I9100T uuids:
0000110a-0000-1000-8000-00805f9b34fb,
00001105-0000-1000-8000-00805f9b34fb,
00001116-0000-1000-8000-00805f9b34fb,
0000112d-0000-1000-8000-00805f9b34fb,
0000112f-0000-1000-8000-00805f9b34fb,
00001112-0000-1000-8000-00805f9b34fb,
0000111f-0000-1000-8000-00805f9b34fb,
00001132-0000-1000-8000-00805f9b34fb,
I get the correct output with phone as commander and tablet as listener:
DeviceListActivity(23121): Received uuids for GT-P5210
DeviceListActivity(23121): ACTION_UUID received for GT-P5210 uuids:
00001105-0000-1000-8000-00805f9b34fb,
0000110a-0000-1000-8000-00805f9b34fb,
0000110c-0000-1000-8000-00805f9b34fb,
00001112-0000-1000-8000-00805f9b34fb,
00001115-0000-1000-8000-00805f9b34fb,
0000111f-0000-1000-8000-00805f9b34fb,
00001200-0000-1000-8000-00805f9b34fb,
3def793a-fa94-4478-ae56-108854b1ef4b,
As you can see, the GUID for my app is listed as the last item. I've tried making the devices discoverable and bonding and unbonding, but the GUID for my app is never returned for the phone. I have other non-Android devices that also use this GUID and they are discovered normally as well.
The phone is running 4.1.2 and the tablet is 4.2.2

Reading raw mouse data on android

In my Android app, I read the values from a 3DConnexion SpaceNavigator via USB-OTG to control an AR.Drone.
Now I want to do the same with a mouse. However, Android is grabbing the mouse and presenting a mouse-cursor. When I write a device-filter with the vendor and product ID of the mouse, I do not get it like with the SpaceNavigator (strangely, both are HID -- I get no cursor with the SpaceNavigator).
Is there a way to get the raw mouse data without the cursor?
Would be perfect with stock Android. but I would also consider altering the ROM for that.
As soon as your Application claims the Mouse (as a USB HID device while being Host), Android should hide the cursor and you can read the raw data. This should work on stock android, but your device has to support USB Host mode and a USB OTG cable will be needed to connect the mouse.
Basic procedure:
enumerate devices
ask for permission to access the USB device
claim the device
read a data package from the HID endpoint
parse the X and Y position, button clicks and scroll wheel rotation from the data package
Example Code that works for me (Android 5.0):
UsbManager usbManager;
UsbDevice usbDevice;
private void connect() {
this.usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
// just get the first enumerated USB device
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
if (deviceIterator.hasNext()) {
this.usbDevice = deviceIterator.next();
}
if (usbDevice == null) {
Log.w(TAG, "no USB device found");
return;
}
// ask for permission
final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
// call method to set up device communication
Log.i(TAG, "permission granted. access mouse.");
// repeat in a different thread
transfer(device);
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
// TODO:
// call your method that cleans up and closes communication with the device
// usbInterface.releaseInterface();
// usbDeviceConnection.close();
}
}
}
};
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
context.registerReceiver(mUsbReceiver, filter);
usbManager.requestPermission(usbDevice, mPermissionIntent);
}
private void transfer(UsbDevice device) {
int TIMEOUT = 0;
boolean forceClaim = true;
// just grab the first endpoint
UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(0);
UsbDeviceConnection connection = this.usbManager.openDevice(device);
connection.claimInterface(intf, forceClaim);
byte[] bytes = new byte[endpoint.getMaxPacketSize()];
connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT);
// depending on mouse firmware and vendor the information you're looking for may
// be in a different order or position. For some logitech devices the following
// is true:
int x = (int) bytes[1];
int y = (int) bytes[2];
int scrollwheel = (int) bytes[3]
// call a listener, process your data ...
}

list connected bluetooth devices?

How can I list all connected bluetooth devices on android ?
thanks!
public void checkConnected()
{
// true == headset connected && connected headset is support hands free
int state = BluetoothAdapter.getDefaultAdapter().getProfileConnectionState(BluetoothProfile.HEADSET);
if (state != BluetoothProfile.STATE_CONNECTED)
return;
try
{
BluetoothAdapter.getDefaultAdapter().getProfileProxy(_context, serviceListener, BluetoothProfile.HEADSET);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private ServiceListener serviceListener = new ServiceListener()
{
#Override
public void onServiceDisconnected(int profile)
{
}
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy)
{
for (BluetoothDevice device : proxy.getConnectedDevices())
{
Log.i("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = "
+ BluetoothProfile.STATE_CONNECTED + ")");
}
BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy);
}
};
As of API 14 (Ice Cream), Android has a some new BluetoothAdapter methods including:
public int getProfileConnectionState (int profile)
where profile is one of HEALTH, HEADSET, A2DP
Check response, if it's not STATE_DISCONNECTED you know you have a live connection.
Here is code example that will work on any API device:
BluetoothAdapter mAdapter;
/**
* Check if a headset type device is currently connected.
*
* Always returns false prior to API 14
*
* #return true if connected
*/
public boolean isVoiceConnected() {
boolean retval = false;
try {
Method method = mAdapter.getClass().getMethod("getProfileConnectionState", int.class);
// retval = mAdapter.getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET) != android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
retval = (Integer)method.invoke(mAdapter, 1) != 0;
} catch (Exception exc) {
// nothing to do
}
return retval;
}
First you need to retrieve the BluetoothAdapter:
final BluetoothAdapter btAdapter =
BluetoothAdapter.getDefaultAdapter();
Second you need to make sure Bluetooth is available and turned on :
if (btAdapter != null && btAdapter.isEnabled()) // null means no
Bluetooth!
If the Bluetooth is not turned out you can either use btAdapter.enable() which is not recommended in the documentation or ask the user to do it : Programmatically enabling bluetooth on Android
Third you need to define an array of states (to filter out
unconnected devices):
final int[] states = new int[] {BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.STATE_CONNECTING};
Fourth, you create a BluetoothProfile.ServiceListener which
contains two callbacks triggered when a service is connected and
disconnected :
final BluetoothProfile.ServiceListener listener = new BluetoothProfile.ServiceListener() {
#Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
}
#Override
public void onServiceDisconnected(int profile) {
}
};
Now since you have to repeat the querying process for all available Bluetooth Profiles in the Android SDK (A2Dp, GATT, GATT_SERVER, Handset, Health, SAP) you should proceed as follow :
In onServiceConnected, place a condition that check what is the current profile so that we add the found devices into the correct collection and we use : proxy.getDevicesMatchingConnectionStates(states) to filter out unconnected devices:
switch (profile) {
case BluetoothProfile.A2DP:
ad2dpDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.GATT: // NOTE ! Requires SDK 18 !
gattDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.GATT_SERVER: // NOTE ! Requires SDK 18 !
gattServerDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.HEADSET:
headsetDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.HEALTH: // NOTE ! Requires SDK 14 !
healthDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.SAP: // NOTE ! Requires SDK 23 !
sapDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
}
And finally, the last thing to do is start the querying process :
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.A2DP);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT_SERVER); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEADSET);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEALTH); // NOTE ! Requires SDK 14 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.SAP); // NOTE ! Requires SDK 23 !
source: https://stackoverflow.com/a/34790442/2715054
So you get the list of paired devices.
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevicesList = btAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedDevicesList) {
Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());
saveValuePreference(getApplicationContext(), pairedDevice.getName(), pairedDevice.getAddress());
}
Android system doesn't let you query for all "currently" connected devices. It however, you can query for paired devices. You will need to use a broadcast receiver to listen to ACTION_ACL_{CONNECTED|DISCONNECTED} events along with STATE_BONDED event to update your application states to track what's currently connected.
I found a solution and it works on android 10
Kotlin
private val serviceListener: ServiceListener = object : ServiceListener {
var name: String? = null
var address: String? = null
var threadName: String? = null
override fun onServiceDisconnected(profile: Int) {}
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
for (device in proxy.connectedDevices) {
name = device.name
address = device.address
threadName = Thread.currentThread().name
Toast.makeText(
this#MainActivity,
"$name $address$threadName",
Toast.LENGTH_SHORT
).show()
Log.i(
"onServiceConnected",
"|" + device.name + " | " + device.address + " | " + proxy.getConnectionState(
device
) + "(connected = "
+ BluetoothProfile.STATE_CONNECTED + ")"
)
}
BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy)
}
}
Call this method in main thread
BluetoothAdapter.getDefaultAdapter()
.getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET)
Java
original code
Please analyze this class online.
Here you will find how to discover all connected (paired) Bluetooth devices.
Well here are the steps:
First, you start intent to discover devices
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
Register a broadcast reciver for it:
registerReceiver(mReceiver, filter);
On the definition of mReceiver:
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
arrayadapter.add(device.getName())//arrayadapter is of type ArrayAdapter<String>
lv.setAdapter(arrayadapter); //lv is the list view
arrayadapter.notifyDataSetChanged();
}
}
and the list will be automatically populated on new device discovery.

Categories

Resources