61 lines
2.0 KiB
Kotlin
61 lines
2.0 KiB
Kotlin
package io.gitlab.jfronny.hc05ac.bt
|
|
|
|
import android.annotation.SuppressLint
|
|
import android.app.Activity
|
|
import android.app.ProgressDialog
|
|
import android.bluetooth.BluetoothSocket
|
|
import android.os.AsyncTask
|
|
import io.gitlab.jfronny.hc05ac.util.btAdapter
|
|
import io.gitlab.jfronny.hc05ac.util.logE
|
|
import io.gitlab.jfronny.hc05ac.util.toast
|
|
import java.io.IOException
|
|
import java.util.*
|
|
|
|
class ConnectBtTask(private val ctx: Ctx) : AsyncTask<Void?, Void?, Void?>() {
|
|
private var connectSuccess = true
|
|
private var progress: ProgressDialog? = null
|
|
private var isBtConnected = false
|
|
override fun onPreExecute() {
|
|
progress = ProgressDialog.show(ctx.context, "Connecting...", "Please Wait!!!")
|
|
}
|
|
|
|
@SuppressLint("MissingPermission")
|
|
override fun doInBackground(vararg devices: Void?): Void? {
|
|
try {
|
|
if (ctx.btSocket == null || !isBtConnected) {
|
|
val bluetoothAdapter = ctx.context.btAdapter
|
|
val dispositivo = bluetoothAdapter.getRemoteDevice(ctx.address)
|
|
ctx.btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(appUUID)
|
|
bluetoothAdapter.cancelDiscovery()
|
|
ctx.btSocket!!.connect()
|
|
}
|
|
} catch (e: IOException) {
|
|
logE("Could not connect", e)
|
|
connectSuccess = false
|
|
}
|
|
return null
|
|
}
|
|
|
|
override fun onPostExecute(result: Void?) {
|
|
super.onPostExecute(result)
|
|
if (!connectSuccess) {
|
|
ctx.context.toast("Connection Failed. Is it a SPP Bluetooth? Try again.")
|
|
ctx.close()
|
|
} else {
|
|
ctx.context.toast("Connected")
|
|
isBtConnected = true
|
|
}
|
|
progress!!.dismiss()
|
|
}
|
|
|
|
interface Ctx {
|
|
val context: Activity
|
|
var btSocket: BluetoothSocket?
|
|
val address: String?
|
|
fun close()
|
|
}
|
|
|
|
companion object {
|
|
val appUUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
|
|
}
|
|
} |