我应该将一些Strings传送到arduino。只是通过而已,什么也不要。 这是我的代码。我是第一次使用android和kotlin。
class Validation : AppCompatActivity() {
lateinit var mmOutputStream: OutputStream
lateinit var mmSocket: BluetoothSocket
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_validation)
resolve_Btn.setOnClickListener {bluetoothAdd() }
}
@SuppressLint("HardwareIds")
private fun bluetoothAdd() {
val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Log.e("Bluetooth ", "not found")
}
if (mBluetoothAdapter!!.isEnabled) {
val pairedDevices = mBluetoothAdapter.bondedDevices
// If there are paired devices
if (pairedDevices.size > 0) {
// Loop through paired devices
for (device in pairedDevices) {
mmSocket= device.createRfcommSocketToServiceRecord(
UUID.fromString("00000000-0000-1000-8000-00805F9B34FB"))
mmSocket.connect()
mmOutputStream = mmSocket.outputStream
val message = "aaa"
val msgBuffer = message.toByteArray(Charset.defaultCharset())
mmOutputStream.write(msgBuffer)
Log.e("Mac Addressess", "are: " + mBluetoothAdapter.getRemoteDevice(device.address))
}
}
}
}
}
现在,当我添加mmSocket !!。connect()时,我抓住了
由以下原因引起:java.lang.reflect.InvocationTargetException 在java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:245) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 由以下原因引起:java.io.IOException:读取失败,套接字可能关闭或超时,读取ret:-1 在android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:706) 在android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:718) 在android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:384) 在com.example.nikita.vas.Validation.bluetoothAdd(Validation.kt:52) 在com.example.nikita.vas.Validation.access $ bluetoothAdd(Validation.kt:21) 在com.example.nikita.vas.Validation $ onCreate $ 1.onClick(Validation.kt:30) 在android.view.View.performClick(View.java:6291) 在android.view.View $ PerformClick.run(View.java:24931) 在android.os.Handler.handleCallback(Handler.java:808) 在android.os.Handler.dispatchMessage(Handler.java:101) 在android.os.Looper.loop(Looper.java:166)
答案 0 :(得分:1)
在访问mmSocket.connect()
对象之前,您忘记了调用outputStream
。
试试这个:
mmSocket= device.createRfcommSocketToServiceRecord(
UUID.fromString("00000000-0000-1000-8000-00805F9B34FB"))
mmSocket.connect()
mmOutputStream = mmSocket!!.outputStream
val message = "aaa"
val msgBuffer = message.toByteArray(Charset.defaultCharset())
mmOutputStream!!.write(msgBuffer)