Discover bluetooth devices android

Bluetooth device discovery in Android — startDiscovery()

Things work (as tested with incremental console logging) up until startDiscovery() .

Frustration:

  • startDiscovery() — I suspect I am passing this in the wrong context. What context does this method need to be placed within to function properly?

If you have been able to get this method working, I would very much appreciate your wisdom.

UPDATE — here’s a stripped down simplified version of the code that is causing me grief; this simplification recapitulates my error. This code runs, it throws no cat.log errors or other errors, it simply doesn’t give any output.

package aqu.bttest; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.widget.Toast; public class BT2Activity extends Activity < private BluetoothAdapter mBTA; private SingBroadcastReceiver mReceiver; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); //register local BT adapter mBTA = BluetoothAdapter.getDefaultAdapter(); //check to see if there is BT on the Android device at all if (mBTA == null)< int duration = Toast.LENGTH_SHORT; Toast.makeText(this, "No Bluetooth on this handset", duration).show(); >//let's make the user enable BT if it isn't already if (!mBTA.isEnabled()) < Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBT, 0xDEADBEEF); >//cancel any prior BT device discovery if (mBTA.isDiscovering()) < mBTA.cancelDiscovery(); >//re-start discovery mBTA.startDiscovery(); //let's make a broadcast receiver to register our things mReceiver = new SingBroadcastReceiver(); IntentFilter ifilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, ifilter); > private class SingBroadcastReceiver extends BroadcastReceiver < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); //may need to chain this to a recognizing function 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 Toast String derp = device.getName() + " - " + device.getAddress(); Toast.makeText(context, derp, Toast.LENGTH_LONG); >> > 

Источник

Discover Bluetooth Devices in Android

Discover Bluetooth Devices in Android

The Android platform support Bluetooth wireless technology, which allows exchanging the data between nearby devices. An application can discover or scan available devices by using Bluetooth API.

If we want to use Bluetooth features, we must declare permissions. The BLUETOOTH permission enables Bluetooth communication and BLUETOOTH_ADMIN permission allows discovering and pair Bluetooth devices.

Also, we must declare ACCESS_FINE_LOCATION permission because a Bluetooth scan can be used to get information about user location.

In the layout XML file, we added the Button element which will used to start scanning for Bluetooth devices.

Using the method ContextCompat.checkSelfPermission() we check if required permission was granted. If not, then we request permission by calling the method ActivityCompat.requestPermissions() .

We need to create and register a BroadcastReceiver . The onReceive() method is invoked when a Bluetooth device is discovered.

The BluetoothAdapter.getDefaultAdapter() method is used to get the Bluetooth adapter. By using the startDiscovery() method, we start discovering devices. The discovery process usually takes about 12 seconds. After that, we can start discovery again if needed.

package com.example.app import android.Manifest import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < private val permission: String = Manifest.permission.ACCESS_FINE_LOCATION private val requestCode: Int = 1 override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val filter = IntentFilter(BluetoothDevice.ACTION_FOUND) registerReceiver(receiver, filter) val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter() myButton.setOnClickListener< if (!bluetoothAdapter.isDiscovering) < bluetoothAdapter.startDiscovery() >> if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED ) < ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode) >> override fun onDestroy() < unregisterReceiver(receiver) super.onDestroy() >private val receiver = object : BroadcastReceiver() < override fun onReceive(context: Context, intent: Intent) < if (intent.action == BluetoothDevice.ACTION_FOUND) < val device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice val deviceName = device.name val deviceMacAddress = device.address Log.d("MY_APP", "$deviceName $deviceMacAddress") >> > >

Display Toast in Android

Send SMS Message in Android

Android allows to send SMS messages directly from an application. Application must have permission to.

Читайте также:  Активировать блютуз ауди а8 д4

Источник

Android — Bluetooth discovery doesn’t find any device

Actually no device is found when i launch the .onDiscovery() method, even though devices are found from Settings/Bluetooth on my Nexus 5.

public class MainActivity extends AppCompatActivity

The filter is working well as far as i could try, i.e ACTION_STATE_CHANGED (on bluetooth enabling) and the two ACTION_DISCOVERY_***.

The following method is then successfuly called:

public void onDiscovery(View view)

And then i have my bluetooth receiver:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) < final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); if (state == BluetoothAdapter.STATE_ON) < showToast("ACTION_STATE_CHANGED: STATE_ON"); >> else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) < mDeviceList = new ArrayList<>(); showToast("ACTION_DISCOVERY_STARTED"); mProgressDlg.show(); > else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action) && !bluetoothSwitchedOFF) < mProgressDlg.dismiss(); showToast("ACTION_DISCOVERY_FINISHED"); Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class); newIntent.putParcelableArrayListExtra("device.list", mDeviceList); startActivity(newIntent); >else if (BluetoothDevice.ACTION_FOUND.equals(action))
    androidbluetoothreceiver
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this question
)">edited Jan 24, 2016 at 15:08
asked Jan 23, 2016 at 16:50
1
    I had the location permission in my manifest using Nexus 5 and I was not finding any devices. The missing thing for me was not asking for location permission in the MainActivity (or whatever activity hosting the search) before searching for devices. That solved the issue for me
    – Khash
    Sep 1, 2019 at 19:30
Add a comment|

3 Answers 3

Reset to default
88

What version of Android are you running this on? If it is Android 6.x, I believe you need to add the ACCESS_FINE_LOCATION permission to your manifest. For example:

I had a similar issue and this fixed it for me.

UPDATE: Adding documentation direct from Google on this:

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions

UPDATE 2020: We recently updated our application to target SDK Version 29. In doing this, our application stopped being able to discover Bluetooth devices again. We have been using ACCESS_COARSE_LOCATION since this answer was originally written. Changing to ACCESS_FINE_LOCATION appears to fix the issue. I now recommend developers try ACCESS_FINE_LOCATION if targeting 29+. Answer updated to reflect this.

Источник

How to scan for available bluetooth devices in range in android?

I need to get a list of available bluetooth devices in the area using google android 2.1. Thing is, i don't just need a list of those devices, i need some unique id for each device found and i need an indicator, how "good" the signal is received (like the "level" in android.wifi.ScanResult). How do i do that?

4 Answers 4

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); 

@SaharMillis: What about it doesn't work for you? It works fine, but your other device needs to be discoverable, not just with bluetooth on.

how does this work if there are multiple bluetooth devices found in the range. Does the receiver get triggered multiple times?

@Zapnologica the BroadcastReceiver gets notified once per device; therefore one has to keep them in an ArrayList field, or alike. while there are two? further actions available, beside the BluetoothDevice.ACTION_FOUND , of which one indicates the scan being complete.

Call method bluetoothScanning, context is required

void bluetoothScanning() < IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); context.registerReceiver(mReceiver, filter); final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.startDiscovery(); >// Create a BroadcastReceiver for ACTION_FOUND. 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(); String deviceHardwareAddress = device.getAddress(); // MAC address Log.i("Device Name: " , "device " + deviceName); Log.i("deviceHardwareAddress " , "hard" + deviceHardwareAddress); >> >; 

Name: LE-Bose Revolve+ SoundLink deviceHardwareAddress: MAC .

@GregD this is my exact problem. it was working fine, but then it started to show only mac addresses and not names. can't figure out why

This code uses BeaconManager, it continuously scans for new Bluetooth devices and returns a Beacons List object which you can use to get what ever information you need.

Make sure you import BeaconManager

private BeaconManager beaconManager; //In onCreate method beaconManager = BeaconManager.getInstanceForApplication(this); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); //use these out of the onCreate method public void onScanStart(View view) < stopScanButton.setEnabled(true); scanningButton.setEnabled(false); beaconManager.bind(this); >@Override public void onBeaconServiceConnect() < beaconManager.removeAllRangeNotifiers(); beaconManager.addRangeNotifier(new RangeNotifier() < @Override public void didRangeBeaconsInRegion(Collectionbeacons, Region region) < for (Beacon b : beacons) < System.out.println(String.format("%s: %f: %d", b.getBluetoothName(), b.getDistance(), b.getRssi())); >); try < //Tells the BeaconService to start looking for beacons that match the passed. beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); >catch (RemoteException e) < Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); >> 

Let me know if that works for you!

To able to discovery devices by bluetooth. Make sure you

  • Enable bluetooth
  • Allow required permissions for your application (some permission is runtime permission). You can check here https://developer.android.com/about/versions/12/features/bluetooth-permissions

AndroidManifest.xml

MainActivity

class MainActivity : AppCompatActivity() < private var bluetoothAdapter: BluetoothAdapter? = null private val bluetoothReceiver: BroadcastReceiver = object : BroadcastReceiver() < override fun onReceive(context: Context?, intent: Intent) < val action = intent.action Log.i("TAG", "onReceive $action") if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) < Log.i("TAG", "Discovery finished, hide loading") >else if (BluetoothDevice.ACTION_FOUND == action) < val device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) Log.i("TAG", "Device Name: " + (device?.name ?: "")) Log.i("TAG", "Device Address:" + (device?.address ?: "")) > > > override fun onCreate(savedInstanceState: Bundle?) < . findViewById(R.id.button_start_discovery).setOnClickListener < if (bluetoothAdapter == null) < initBluetoothDiscovery() >startDiscovery() > > private fun initBluetoothDiscovery() < val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager bluetoothAdapter = bluetoothManager.adapter val intentFilter = IntentFilter().apply < addAction(BluetoothDevice.ACTION_FOUND) addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) >registerReceiver(bluetoothReceiver, intentFilter) > private fun startDiscovery() < if (bluetoothAdapter?.isDiscovering == true) < Log.i("TAG", "cancel start discovery") bluetoothAdapter?.cancelDiscovery() >Log.i("TAG", "start discovery, show loading") bluetoothAdapter?.startDiscovery() > override fun onDestroy() < super.onDestroy() bluetoothAdapter?.cancelDiscovery(); unregisterReceiver(bluetoothReceiver); >> 

Источник

How to Make Bluetooth Discoverable to Other Devices in Android?

In android devices, Bluetooth is a communication network protocol that allows devices to connect wirelessly to exchange data with other Bluetooth devices. In general, we can make use of Bluetooth API to implement Bluetooth functionalities, such as enable or disable Bluetooth, searching for available Bluetooth devices, connecting with the devices, and managing the data transfer between devices within the range. In Android, BluetoothAdapter class performs all Bluetooth related activities. By default, and Bluetooth device is in an undiscoverable mode. This means that if we switch on the Bluetooth in a device, it is visible only to those paired earlier with it. This device is invisible on devices other than the paired ones. To make this device visible, we switch on the Discoverable option, which makes the device global to its vicinity. This device now shows up on every list, be it the new devices or the earlier paired ones. Applications involving the pairing of a music device or a digital watch (syncing by Bluetooth transfers) with other devices are quite simple. These devices are set global, and any other device can discover them. To make this thing possible on an Android mobile, one can go to the Bluetooth settings and make it global or discoverable. This article wants to share with you the implementation of an application that makes the device’s Bluetooth discoverable when the Bluetooth is switched on. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.

Implementation

  • The application explained in this article is basically to test if we can invoke methods programmatically to fulfill our purpose.
  • We created an Android mobile application consisting of three buttons; Turn ON, Discoverable, and Turn OFF, having the functionalities invoke various Bluetooth adapter methods.
  • This application’s changes are global, i.e., Bluetooth will continue to be switched on if the Turn OFF button is not clicked, or any other relatable version.
  • To make the device discoverable on other devices list, a new activity must be initialized using startActivityForResult(intent, int) with the ACTION_REQUEST_DISCOVERABLE intent.

Note: It is important for the Bluetooth to be present and in a power-on mode to make it discoverable.

Step by Step Implementation

To programmatically show a list of Bluetooth Paired devices against our device in Android, follow the following steps:

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Woking with the AndroidManifest.xml file

Go to the AndroidManifest.xml file and add these permissions required by the Bluetooth adapter: BLUETOOTH, BLUETOOTH_ADMIN, and ACCESS_COARSE_LOCATION.

Below is the complete code for the AndroidManifest.xml file.

Источник

Оцените статью
Adblock
detector