Android scan bluetooth devices code

detect bluetooth Le devices in Android

I’m a beginner in android app development. I’ve tried reading the documentation but am getting nowhere (functions in Android’s tutorial such as StartLeScan() have been deprecated, etc. ) Is there a simple function that returns a list of bluetooth devices ? something like getDevices() -> (list of devices) ? Thank you

4 Answers 4

basically it depends on which android version you are targeting. since the api has changed a bit in lollipop (21).

in your activity, get the bluetooth adapter

BluetoothManager bm = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE) BluetoothAdapter mBluetoothAdapter = bm.getAdapter(); // Ensures Bluetooth is available on the device and it is enabled. If not, // displays a dialog requesting user permission to enable Bluetooth. if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled())

then you should check which android version you are targeting

int apiVersion = android.os.Build.VERSION.SDK_INT; if (apiVersion > android.os.Build.VERSION_CODES.KITKAT) < BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner(); // scan for devices scanner.startScan(new ScanCallback() < @Override public void onScanResult(int callbackType, ScanResult result) < // get the discovered device as you wish // this will trigger each time a new device is found BluetoothDevice device = result.getDevice(); >>); > else < // targetting kitkat or bellow mBluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() < @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) < // get the discovered device as you wish >>); // rest of your code that will run **before** callback is triggered since it's asynchronous 

dont forget to add permissions in your manifest

Читайте также:  Как проверить работает ли bluetooth

Источник

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 .

Читайте также:  Иконка блютуз пропала windows 10

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

Источник

Читайте также:  Bluetooth наушники есть эквалайзер

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Create a Bluetooth Scanner With Android’s Bluetooth API

tutsplus/Android-BluetoothScannerFinishedProject

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Tuts+ Tutorial: Create a Bluetooth Scanner With Android’s Bluetooth API

In this tutorial, we explore what Bluetooth is and how to use the Android Bluetooth API to create an app that scans and displays nearby Bluetooth devices. Additionally, we look over the basics of connecting with a nearby Bluetooth device.

Read this tutorial on Tuts+

About

Create a Bluetooth Scanner With Android’s Bluetooth API

Источник

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