I've got my SettingsActivity
allowing the user to choose form a list of paired Bluetooth devices.
However, there seems to be something strange going on with Bluetooth Low Energy where devices don't pair normally: the device I'm trying to connect to won't pair to any of my android devices, and I notice that my Fitbit isn't is the list of paired devices on my phone even though it seems to be working. WTF?
Anyway, the question is: how do I add to the list of proper devices the list of BLE devices?
(I've looked at https://developer.android.com/guide/topics/connectivity/bluetooth-le#find but it's just disjointed bits of unexplained code; it doesn't say where to put them, how to call them, or how they fit together, and if I copy it then it comes up with loads of errors.)
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// get bluetooth devices
var btDevices: Array<CharSequence> = arrayOf("")
try {
val bt: BluetoothManager =
getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager;
val bta: BluetoothAdapter = bt.adapter;
// Get normal Bluetooth devices.
val pairedDevices: Set<BluetoothDevice> = bta.bondedDevices
// Get Bluetooth Low Energy devices.
// HOW?!
btDevices = pairedDevices.map { z -> z.name }.toTypedArray()
}
catch(e:Exception) {}
// Start the fragment
setContentView(R.layout.settings_activity)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings, SettingsFragment(cs))
.commit()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Slap the toolbar.
val toolbar = findViewById<Toolbar>(R.id.settings_toolbar) // Must be after setContentView or else it returns null.
setSupportActionBar(toolbar)
toolbar.setNavigationOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
finish()
}
})
}
class SettingsFragment(adapters: Array<CharSequence>) : PreferenceFragmentCompat() {
private var adapters: Array<CharSequence> = adapters
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
val p:ListPreference? = findPreference<ListPreference>("bluetoothName")
p?.setEntries(adapters)
p?.setEntryValues(adapters)
}
}
}