Java反射调用createInsecureRfcommSocket方法的Kotlin实现咨询
正确实现代码
你原有代码存在两处核心问题:一是没有使用反射调用返回的socket实例,反而创建了基于UUID的标准API socket;二是反射逻辑放在类初始化块,没有做异常处理,容易触发崩溃。
以下是可直接运行的正确Kotlin实现:
import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothSocket import android.util.Log import java.io.IOException class BluetoothClient(private val device: BluetoothDevice) : Thread() { // 要连接的蓝牙端口号 private val btPort = 5 // 反射创建的socket实例 private var deviceSocket: BluetoothSocket? = null // 要发送的消息,根据你的业务需求赋值即可 private val message = "你的待发送内容" override fun run() { try { // 反射调用createInsecureRfcommSocket方法 val createRfcommMethod = device::class.java.getMethod( "createInsecureRfcommSocket", Int::class.javaPrimitiveType ) deviceSocket = createRfcommMethod.invoke(device, btPort) as BluetoothSocket // 判空处理 val socket = deviceSocket ?: throw IOException("反射创建socket失败") Log.i("client", "开始连接") socket.connect() Log.i("client", "开始发送数据") val outputStream = socket.outputStream val inputStream = socket.inputStream try { outputStream.write(message.toByteArray()) outputStream.flush() Log.i("client", "数据发送成功") } catch (e: Exception) { Log.e("client", "数据发送失败", e) } finally { outputStream.close() inputStream.close() socket.close() } } catch (e: Exception) { Log.e("client", "连接流程失败", e) deviceSocket?.close() } } }
实现说明
- 这里用了Java反射API实现,相比Kotlin反射不需要额外引入kotlin-reflect依赖,包体积更小,性能也更优
- 所有异常统一捕获处理,避免崩溃,异常触发时也会主动关闭已创建的socket资源,防止内存泄漏
- 反射调用的方法参数明确指定为int基本类型,和原生方法参数完全匹配,不会出现方法找不到的问题
内容的提问来源于stack exchange,提问作者Stigma
相关产品推荐
相关产品推荐

