Search bluetooth device android

Как сделать поиск доступных bluetooth устройств под андроид в xamarin

Так как под рукой не оказалось Xamarin — пишу ответ, основываясь на документации к методам, классам и свойствам, а также основываясь на найденные ответы.

1) Необходимо получить экземпляр BluetoothAdapter на текущем устройстве и проверить, включен ли он

2) Необходимо получить все физические устройства, существующие как сопряженные устройства с текущим устройством, для этого нужно использовать коллекцию BondedDevices из полученного ранее адаптера.

Теперь код, который должен нам помочь:

// получить адаптер по-умолчанию BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter; // проверяем, что у нас получен адаптер (есть Bluetooth) и он включен if (adapter != null && adapter.isEnabled) < // получим список связанных устройств ICollectiondevices = adapter.BondedDevices; // инициализируем пустой список строк имен устройств List names = new List(); // пройдем по списку устройств и будем заполнять список имен foreach (var device in devices) < // device - сопряженное устройство из BondedDevices names.Add(device.Name); // добавление имени >> 

В дополнение к ответу добавлю код, который будет выводить в список еще и новые устройства, находящиеся рядом, для этого потребуется написать свой перегруженный метод OnReceive в классе, наследующем BroadcastReceiver :

class BluetoothDeviceReceiver : BroadcastReceiver < // перегрузим метод `OnReceive` public override void OnReceive(Context context, Intent intent) < // это действие, которое будем выполнять (для нас пока будет только поиск) String action = intent.Action; if (action == BluetoothDevice.ActionFound) < // Получить устройство BluetoothDevice newDevice = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice); // если устройство не сопряжено (его еще не было в BondedDevices) if (newDevice.BondState != Bond.Bonded) < // нужно учитывать, что переменная `names` должна быть в области видимости names.Add(newDevice.Name); // добавление имени >> // далее можно описать и другое действие, к примеру остановка поиска // это будет action = BluetoothAdapter.ActionDiscoveryFinished > > 

Затем, чтобы использовать написанный класс — необходим следующий код:

// создадим фильтр с указанным дейсвтием - поиск IntentFilter filter = new IntentFilter(BluetoothDevice.ActionFound); // наш ранее описанный ресивер, для поиска по указанному фильтру BluetoothDeviceReceiver receiver = new BluetoothDeviceReceiver(); // зарегистрируем трансляцию(ресивер) и фильтр для обнаружения устройств RegisterReceiver(receiver, filter); // запустим поиск, это тот же адаптер из `BluetoothAdapter.DefaultAdapter` adapter.StartDiscovery(); 

Также, чтобы не было глюков в приложении я рекомендую описать действие для BluetoothAdapter.ActionDiscoveryFinished — запускается он точно так же, как и BluetoothDevice.ActionFound , но только позже. И не забыть освободить занятый ресурс транслятора (ресивера), через метод UnregisterReceiver . Дополнительный пример кода можно найти вот тут: Bluetooth Chat DeviceListActivity

Ссылки на полезные источники:

Источник

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

Источник

Читайте также:  Work headphones with bluetooth

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

Источник

How to discover Bluetooth devices Programatically in android and display in Listview

I tried and followed some tutorial on web but it didn’t work on new Android versions. I declared all Bluetooth permissions and used Dexter permission library. I followed few answers but it doesn’t display available Bluetooth device name also Below is my code:

@Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); scan.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < toast("starts scanning. "); mBluetoothAdapter.startDiscovery(); >>); mAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() < @Override public void onItemClick(AdapterViewadapterView, View view, int i, long l) < String bluetoothDevice = mAdapter.getItem(i); toast(bluetoothDevice); >>); > public void pairedDevicesListView(View view) < mAdapter.clear(); pairedDevices = mBluetoothAdapter.getBondedDevices(); for (BluetoothDevice device : pairedDevices)< mAdapter.add(device.getName() + "\n" + device.getAddress()); >> > 

I tried all the answers you could not try them all. So tell us what exactly you have tried? And what exactly didn’t work?

I am able to turn it on and off even it displaying paired devices but not newly discovered device list. please check my code I edited my question

5 Answers 5

To discover a device, first get the bluetooth adapter by calling BluetoothAdapter.getDefaultAdapter()

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 

To start discover, simply call the startDiscovery() from bluetooth adapter. This process is asynchronous so it will return immediately. To catch the discovery process, we can register a BroadcastReceiver with ACTION_FOUND, ACTION_DISCOVERY_STARTED, ACTION_DISCOVERY_STARTED. For each device found, the intent will carry extra field EXTRA_DEVICE containg the BluetoothDevice object.

IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(mReceiver, filter); adapter.startDiscovery(); 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) < //discovery starts, we can show progress dialog or perform other tasks >else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < //discovery finishes, dismis progress dialog >else if (BluetoothDevice.ACTION_FOUND.equals(action)) < //bluetooth device found BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); showToast("Found device " + device.getName()); >> >; 

And, don’t forget to unregister the receiver on Activity’s onDestroy method:

@Override public void onDestroy()

Add manifest permissions as follows

protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnstart=findViewById(R.id.btnstart); mListView=findViewById(R.id.listofdevices); final ArrayAdapter mAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1); mListView.setAdapter(mAdapter); txt1=findViewById(R.id.txt1); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); setdevicevisible(); boolean hasBluetooth = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH); if(!hasBluetooth) < AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create(); dialog.setTitle(getString(R.string.bluetooth_not_available_title)); dialog.setMessage(getString(R.string.bluetooth_not_available_message)); dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() < public void onClick(DialogInterface dialog, int which) < // Closes the dialog and terminates the activity. dialog.dismiss(); MainActivity.this.finish(); >>); dialog.setCancelable(false); dialog.show(); > if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) < ActivityCompat.requestPermissions((Activity) this, new String[], 1); > // If another discovery is in progress, cancels it before starting the new one. if (mBluetoothAdapter.isDiscovering()) < mBluetoothAdapter.cancelDiscovery(); >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 mAdapter.add(device.getName() + "\n" + device.getAddress()); >> >; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); > 

I forgot to declare Location permissions in the manifest file. To discover Bluetooth devices programmatically you need to add two permission i.e. ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.

Читайте также:  Steelseries arctis 5 bluetooth

You could use the MAC address as unique ID.

And you can find in the official doc here a complete example of it

About signal strength i think you should use RSSI (Received Signal Strength Indicator)

Edit: An easy way to accomplish this will be like this snippet to find bluetooth devices

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

Try using this code, it worked for me.

public class DeviceListActivity extends Activity < private ListView pairedDevicesListView, newDevicesListView; private ArrayListdataList= new ArrayList(); private ArrayList pairedDevices=new ArrayList(); private BluetoothAdapter bluetoothAdapter; BluetoothDevice device; private ArrayAdapter newDeviceAdapter; private DeviceListAdapter pairedDeviceAdapter; public static String DEVICE_ADDRESS = "device_address"; private IntentFilter filter; private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); Log.e("action", action); // Toast.makeText(DeviceListActivity.this, action, Toast.LENGTH_SHORT).show(); device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (action.equals(BluetoothDevice.ACTION_FOUND)) < device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() != BluetoothDevice.BOND_BONDED) < newDeviceAdapter.add(device.getName() + "\n" + device.getAddress()); pairedDevices.add(device); newDeviceAdapter.notifyDataSetChanged(); >> else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) < if (newDeviceAdapter.getCount() == 0) < Toast.makeText(DeviceListActivity.this, "No devices found", Toast.LENGTH_SHORT).show(); newDeviceAdapter.add("No new device found"); newDeviceAdapter.notifyDataSetChanged(); >> > >; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_device_list); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); pairedDevicesListView = (ListView) findViewById(R.id.avail_devices); newDevicesListView=(ListView)findViewById(R.id.new_devices); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); pairedDeviceAdapter = new DeviceListAdapter(this,dataList, pairedDevices); pairedDevicesListView.setAdapter(pairedDeviceAdapter); pairedDeviceAdapter.notifyDataSetChanged(); //----------------------------------------------- newDeviceAdapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1); newDevicesListView.setAdapter(newDeviceAdapter); newDeviceAdapter.notifyDataSetChanged(); if (bluetoothAdapter.isDiscovering()) < bluetoothAdapter.cancelDiscovery(); >bluetoothAdapter.startDiscovery(); // get paired devices Set pairedDevice = bluetoothAdapter.getBondedDevices(); if(pairedDevice.size()>0) < // pairedDeviceAdapter.clear(); for(BluetoothDevice device : pairedDevice) < // pairedDeviceAdapter.add(device.getName()+ "\n" +device.getAddress()); dataList.add(new DeviceData(device.getName(),device.getAddress())); pairedDevices.add(device); >pairedDeviceAdapter.notifyDataSetChanged(); > // register broadcast receiver filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(broadcastReceiver, filter); pairedDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() < @Override public void onItemClick(AdapterViewparent, View view, int position, long id) < bluetoothAdapter.cancelDiscovery(); String data = ((TextView) view).getText().toString(); String address = data.substring(data.length() - 17); Intent intent = new Intent(); intent.putExtra("device_address", address); intent.putExtra("info", data); setResult(Activity.RESULT_OK, intent); finish(); >>); newDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() < @Override public void onItemClick(AdapterViewparent, View view, int position, long id) < bluetoothAdapter.cancelDiscovery(); Boolean isBonded = false; try < isBonded = createBond(device); if(isBonded) < Log.i("Log","Paired"); // pairedDeviceAdapter.add(device.getName() + "\n" + device.getAddress()); dataList.add(new DeviceData(device.getName(),device.getAddress())); newDeviceAdapter.remove(device.getName() + "\n" + device.getAddress()); pairedDeviceAdapter.notifyDataSetChanged(); newDeviceAdapter.notifyDataSetChanged(); // Toast.makeText(DeviceListActivity.this, "paired to:" +device.getName(), Toast.LENGTH_SHORT).show(); // ------------------------ // Intent intent = new Intent(); // intent.putExtra("device_address", device.getAddress()); // intent.putExtra("info", device.getName()); // setResult(Activity.RESULT_OK, intent); // finish(); >> catch (Exception e) < e.printStackTrace(); >> >); > @Override protected void onStart() < super.onStart(); registerReceiver(broadcastReceiver, filter); >@Override protected void onPostResume() < super.onPostResume(); registerReceiver(broadcastReceiver, filter); >@Override protected void onDestroy() < super.onDestroy(); if (bluetoothAdapter != null) < bluetoothAdapter.cancelDiscovery(); >this.unregisterReceiver(broadcastReceiver); > public boolean createBond(BluetoothDevice btDevice) throws Exception < Class class1 = Class.forName("android.bluetooth.BluetoothDevice"); Method createBondMethod = class1.getMethod("createBond"); Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); return returnValue.booleanValue(); >> 

Источник

Читайте также:  Mini one bluetooth kit

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

Источник

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