我有一个设备,当我向其发送字符串cmdc
时,它将返回一个6位整数。将此称为“计数命令”。我目前正在使用BtChat从设备发送和接收数据。设备是服务器。我的应用将是客户端。
这是我配对时用于将字符串发送到服务器的功能:
@Throws(IOException::class)
fun sendData(socket: BluetoothSocket? , data : String) {
val toSend = data.toByteArray()
val outputStream = socket!!.outputStream
outputStream.write(toSend)
outputStream.flush()
outputStream.close()
}
从我自己的应用程序而不是BtChat发出命令后,如何接收整数?
我尝试使用以下类来监听服务器:
class ServerConnectThread(mBTSocket: BluetoothSocket?) : Thread() {
private var bTSocket: BluetoothSocket? = mBTSocket
fun acceptConnect(bTAdapter: BluetoothAdapter, mUUID: UUID) {
var temp: BluetoothServerSocket? = null
try {
temp = bTAdapter.listenUsingRfcommWithServiceRecord("Dual-SPP", mUUID)
// TODO: What should I do with the server socket?
// Loop on a background thread until an integer is discovered?
// When I print 'temp' I get the following:
// ServerSocket: Type: TYPE_RFCOMM Channel: -1
} catch (e: IOException) {
Log.d("SERVERCONNECT", "Could not get a BluetoothServerSocket:" + e.toString())
}
while (true) {
try {
bTSocket = temp!!.accept()
} catch (e: IOException) {
Log.d("SERVERCONNECT", "Could not accept an incoming connection.")
break
}
if (bTSocket != null) {
try {
temp.close()
} catch (e: IOException) {
Log.d("SERVERCONNECT", "Could not close ServerSocket:" + e.toString())
}
break
}
}
}
fun closeConnect() {
try {
bTSocket!!.close()
} catch (e: IOException) {
Log.d("SERVERCONNECT", "Could not close connection:" + e.toString())
}
}
}
我应该在哪里上这堂课?发出命令后,服务器似乎在“发射”整数。如何捕获返回的值并将其存储在我的应用程序中?
我当时想我可能会在配对后立即在JobIntentService中连接到服务器,但目前不适用于我:
class BluetoothService : JobIntentService() {
var bluetoothDevice: BluetoothDevice? = null
internal val mHandler = Handler()
override fun onHandleWork(intent: Intent) {
// We have received work to do. The system or framework is already
// holding a wake lock for us at this point, so we can just go.
Log.i("SimpleJobIntentService", "Executing work: $intent")
bluetoothDevice = intent.extras!!.getParcelable("btdevice")
Log.d("CONNECTED ", bluetoothDevice!!.name)
val i = Intent(baseContext, MainActivity::class.java)
i.putExtra("btdevice_connected", bluetoothDevice)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
application.startActivity(i)
val deviceName = bluetoothDevice!!.name
//println(deviceName)
val mUUID = bluetoothDevice!!.uuids[0].uuid
//println(mUUID)
ServerConnectThread().run {
acceptConnect(BluetoothAdapter.getDefaultAdapter(), deviceName, mUUID)
}
}
override fun onDestroy() {
super.onDestroy()
// toast("All work complete")
}
// Helper for showing tests
internal fun toast(text: CharSequence) {
mHandler.post { Toast.makeText(this@BluetoothService, text, Toast.LENGTH_SHORT).show() }
}
companion object {
/**
* Unique job ID for this service.
*/
internal val JOB_ID = 1000
/**
* Convenience method for enqueuing work in to this service.
*/
internal fun enqueueWork(context: Context, work: Intent, btdevicE_JOB_ID: Int) {
JobIntentService.enqueueWork(context, BluetoothService::class.java, btdevicE_JOB_ID, work)
}
}