BtMonitor Kotlin | #4

ControlActivity

import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.neco_desarrollo.btmonitorkotlin.databinding.ActivityControlBinding

class ControlActivity : AppCompatActivity() {
private lateinit var binding: ActivityControlBinding
private lateinit var actListLauncher: ActivityResultLauncher<Intent>
lateinit var btConnection: BtConnection
private var listItem: ListItem? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityControlBinding.inflate(layoutInflater)
setContentView(binding.root)
onBtListResult()
init()

}

private fun init(){
val btManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val btAdapter = btManager.adapter
btConnection = BtConnection(btAdapter)
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.control_menu, menu)
return super.onCreateOptionsMenu(menu)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.id_list){
actListLauncher.launch(Intent(this, BtListActivity::class.java))
} else if(item.itemId == R.id.id_connect){
listItem.let {
btConnection.connect(it?.mac!!)
}
}
return super.onOptionsItemSelected(item)
}

private fun onBtListResult(){
actListLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()){
if(it.resultCode == RESULT_OK){
listItem = it.data?.getSerializableExtra(BtListActivity.DEVICE_KEY) as ListItem
}
}
}
}

BtConnection

import android.bluetooth.BluetoothAdapter

class BtConnection(private val adapter: BluetoothAdapter) {
lateinit var cThread: ConnectThread
fun connect(mac: String) {
if (adapter.isEnabled && mac.isNotEmpty()) {
val device = adapter.getRemoteDevice(mac)
device.let {
cThread = ConnectThread(it)
cThread.start()
}
}
}
}

ConnectThread

import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.util.Log
import java.io.IOException
import java.util.*

class ConnectThread(private val device: BluetoothDevice) : Thread() {
val uuid = "00001101-0000-1000-8000-00805F9B34FB"
var mSocket: BluetoothSocket? = null

init {
try {
mSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(uuid))
}catch (i: IOException){

}
}

override fun run() {
try {
Log.d("MyLog","Connecting...")
mSocket?.connect()
Log.d("MyLog","Connected")
}catch (i: IOException){
Log.d("MyLog","Can not connect to device")
closeConnection()
}
}

fun closeConnection(){
try {
mSocket?.close()
}catch (i: IOException){

}
}
}

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *