- Bluetooth device discovery in Android — startDiscovery()
- Discover Bluetooth Devices in Android
- Related
- Android — Bluetooth discovery doesn’t find any device
- How to scan for available bluetooth devices in range in android?
- 4 Answers 4
- How to Make Bluetooth Discoverable to Other Devices in Android?
- Implementation
- Step by Step Implementation
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
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") >> > >
Related
Android allows to send SMS messages directly from an application. Application must have permission to.
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))/ When discovery finds a device // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); mDeviceList.add(device); showToast("Device found mt24 mb12">androidbluetoothreceiver