ScanActivity.kt 2.4 KB
Newer Older
Anon's avatar
Anon committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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() {

Anon's avatar
Anon committed
17 18 19 20 21
    // TODO: Figure out how to transfer this later
    companion object {
        var selectedDevice: BluetoothDevice? = null
    }

Anon's avatar
Anon committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
    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

Anon's avatar
Anon committed
40 41 42 43 44 45 46 47 48 49
        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)
            }
        }

Anon's avatar
Anon committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        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 (!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)
    }
}