我有点绝望。我开发了一个Android应用程序,它可以连接到Adafruit Bluefruit。我观看了很多教程并尝试了很多想法。使用nRF Connect应用程序,我可以连接智能手机和蓝莓,但使用我自己的应用程序,它是不可能的。 我不明白为什么找不到解决方案。
这是连接代码的一部分:
private class ConnectToDevice(c: Context) : AsyncTask<Void, Void, String>() {
//create member variables
private var connectSuccess: Boolean = true
private val context: Context
//create an constructor
init {
this.context = c
}
override fun onPreExecute() {
super.onPreExecute()
m_progress = ProgressDialog.show(context, "Connecting...", "please wait")
}
override fun doInBackground(vararg p0: Void?): String? {
try {
if (m_bluetoothSocket == null || !m_isConnected){
m_bluetoothAdapter= BluetoothAdapter.getDefaultAdapter()
//create bluetooth device, by mac-address
val device: BluetoothDevice = m_bluetoothAdapter.getRemoteDevice(m_address)
//sets up connection between phone and bluetooth device
m_bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(m_myUUID)
//stopps looking for devices
BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
//connects bluetooth device
m_bluetoothSocket!!.connect()
}
} catch (e: IOException){
connectSuccess = false
e.printStackTrace()
}
return null
}
代码基于这个很棒的教程:https://github.com/appsinthesky/Kotlin-Bluetooth
我得到以下Logcat:
W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
...
W/System.err: ControlActivity$ConnectToDevice.doInBackground(ControlActivity.kt:104)
W/System.err: at ControlActivity$ConnectToDevice.doInBackground(ControlActivity.kt:79)
...
I/data: couldn't connect
我希望,任何人都可以帮助我! 非常感谢提前!
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="bluetoothle">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".SelectDeviceActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ControlActivity"
android:screenOrientation="portrait"/>
</application>