android取得藍芽裝置連線狀態

Java

public static boolean isConnected(BluetoothDevice device) {
    try {
        Method m = device.getClass().getMethod("isConnected", (Class[]) null);
        boolean connected = (boolean) m.invoke(device, (Object[]) null);
        return connected;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

Kotlin

fun isConnected(device: BluetoothDevice): Boolean {
  return try {
    val m: Method = device.javaClass.getMethod("isConnected")
    m.invoke(device) as Boolean
  } catch (e: Exception) {
    throw IllegalStateException(e)
  }
}

發表迴響