android takes example code for nearby Bluetooth devices and calculates distance

  • 2021-08-12 03:34:57
  • OfStack

Need a local Bluetooth adapter


//  Get the local Bluetooth adapter 
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

Determine whether Bluetooth is supported and confirm that it is turned on.


//  Determine whether the mobile phone supports Bluetooth 
 if (mBluetoothAdapter == null) {
  Toast.makeText(this, " The device does not support Bluetooth ", Toast.LENGTH_SHORT).show();
  finish();
 }
 //  Determine whether to turn on Bluetooth 
 if (!mBluetoothAdapter.isEnabled()) {
  //  Open after the pop-up dialog box prompts the user yes 
  Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  startActivityForResult(intent, 1);
  //  Forcibly open it without prompting 
  // mBluetoothAdapter.enable();
 }else {
  //  Forcibly open it without prompting 
   mBluetoothAdapter.enable();
 }

Get the Bluetooth device whose mobile phone has been paired


//  Get paired devices 
 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
   .getBondedDevices();
 //  Determine whether there are paired devices 
 if (pairedDevices.size() > 0) {
  for (BluetoothDevice device : pairedDevices) {
   //  Traversal 
   mDevicesList.add(device.getAddress());
   tvDevices.append(device.getName() + ":" + device.getAddress() + "\n");
  }
 }

Register Asynchronous Search Broadcast for Bluetooth Devices


//  Find the broadcast of the device 
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//  Registered broadcast 
registerReceiver(receiver, filter);
//  Search for completed broadcasts 
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//  Registered broadcast 
registerReceiver(receiver, filter);

The Method of Searching for Bluetooth


 private void scanBluth() {
//  Set the progress bar 
setProgressBarIndeterminateVisibility(true);
setTitle(" Searching ...");
//  Determine whether you are searching , If you are searching, cancel the search 
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
//  Start a search 
mBluetoothAdapter.startDiscovery();
}

Broadcast receiver


 private final BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
  //  Types of broadcasts received 
  String action = intent.getAction();
  //  Discover the broadcast of the device 
  if (BluetoothDevice.ACTION_FOUND.equals(action)) {
   //  From intent Get devices in 
   BluetoothDevice device = intent
     .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
   String aa = tvDevices.getText().toString() + "";
   if (aa.contains(device.getAddress())) {
    return;
   } else {
    //  Judge whether it has been paired 
    if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
     //  Add to list 
     short rssi = intent.getExtras().getShort(
       BluetoothDevice.EXTRA_RSSI);
     int iRssi = abs(rssi);
 //  Convert Bluetooth signal strength to distance 
     double power = (iRssi - 59) / 25.0;
     String mm = new Formatter().format("%.2f", pow(10, power)).toString();
     tvDevices.append(device.getName() + ":"
       + device.getAddress() + "  : " + mm + "m" + "\n");
    }else {
    }
   }
   //  Search complete 
  } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
    .equals(action)) {
   //  Close the progress bar 
   setProgressBarIndeterminateVisibility(true);
   setTitle(" Search complete! ");
   mBLHandler.sendEmptyMessageDelayed(1, 1000);
  }
 }
};

I added Handler for cyclic scanning in the code


//  Used for cyclic scanning of Bluetooth hangdler
Handler mBLHandler = new Handler() {
 @Override
 public void handleMessage(Message msg) {
  super.handleMessage(msg);
  switch (msg.what) {
   case 1:
    scanBluth();
    break;
   default:
    break;
  }
 }
};

In the project, one permission manager written in the early stage is used. Look at the front specifically. Address:

https://www.ofstack.com/article/133350.htm

The permissions used are


// Bluetooth function can be used normally only if all mobile phones need permissions 
 <uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
// Some mobile phones (such as Xiaomi, etc.) need to add the following two permissions to make Bluetooth function work normally 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Related articles: