ScanActivity.kt 2.21 KB
Newer Older
Anon's avatar
Anon committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
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() {

    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

        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<BluetoothDevice>()

        val leScanCallback = BluetoothAdapter.LeScanCallback { device, _, _ ->
//            if (device.name == targetDeviceName) {
//                if (!connected) {
//                    connected = true
//                    bluetoothGatt = device.connectGatt(this, true, gattCallback, BluetoothDevice.TRANSPORT_LE)
//                }
//            }

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