Reputation: 39
I should transfer some Strings to arduino. Just only pass, do not take anything. This my code. I'm working with android and kotlin for the first time.
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))
}
}
}
}
}
Now when I added mmSocket!!.connect(), I catch this
Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) Caused by: java.io.IOException: read failed, socket might closed or timeout, read ret: -1 at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:706) at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:718) at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:384) at com.example.nikita.vas.Validation.bluetoothAdd(Validation.kt:52) at com.example.nikita.vas.Validation.access$bluetoothAdd(Validation.kt:21) at com.example.nikita.vas.Validation$onCreate$1.onClick(Validation.kt:30) at android.view.View.performClick(View.java:6291) at android.view.View$PerformClick.run(View.java:24931) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:101) at android.os.Looper.loop(Looper.java:166)
Upvotes: 2
Views: 1672
Reputation: 692
You forgot to call mmSocket.connect()
before accessing outputStream
object.
Try this:
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)
Upvotes: 3