package com.github.antweb.donkey import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Handler import android.widget.ListView import androidx.appcompat.app.AppCompatActivity private const val TAG = "ScanActivity" class ScanActivity : AppCompatActivity() { // HACK: Figure out how to transfer this later companion object { var selectedDevice: BluetoothDevice? = null } private lateinit var listView: ListView private lateinit var listAdapter: DeviceListAdapter private var mScanning = false private val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) { val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager bluetoothManager.adapter } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_scan) listView = findViewById(R.id.list_view_devices) listAdapter = DeviceListAdapter(applicationContext) listView.adapter = listAdapter listView.setOnItemClickListener { adapterView, view, i, l -> val item = adapterView.adapter.getItem(i) as? BluetoothDevice if (item != null) { selectedDevice = item val intent = Intent(this, SendActivity::class.java) startActivity(intent) } } checkPermissions() scan() } private fun checkPermissions() { bluetoothAdapter?.takeIf { !it.isEnabled }?.apply { val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) startActivity(enableBtIntent) } } private fun scan() { val foundDevices = mutableSetOf() val leScanCallback = BluetoothAdapter.LeScanCallback { device, _, _ -> if (!foundDevices.contains(device)) { foundDevices.add(device) listAdapter.add(device) } } // Stops scanning after a pre-defined period Handler().postDelayed({ mScanning = false bluetoothAdapter?.stopLeScan(leScanCallback) }, 5000) mScanning = true bluetoothAdapter?.startLeScan(leScanCallback) } }