【问题标题】:How to send a text message to a paired device through bluetooth in android?如何通过android中的蓝牙向配对设备发送短信?
【发布时间】:2014-01-31 09:45:56
【问题描述】:

在我的应用程序中,我想通过蓝牙发送和接收短信。我可以在我的列表视图中看到配对设备名称和地址的列表。但是当我尝试向配对设备发送文本时没有任何反应。在其他设备中没有收到文本。

这是我向配对设备发送消息的代码。

private void sendDataToPairedDevice(String message, String adress) {
        byte[] toSend = message.getBytes();
        try {
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adress);
            // BluetoothSocket socket
            // =device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
            BluetoothSocket socket = null;
            Method m = null;
            try {
                m = device.getClass().getMethod("createRfcommSocket",
                        new Class[] { int.class });
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                socket = (BluetoothSocket) m.invoke(device, 1);
            } catch (Exception e) {
                e.printStackTrace();
            }

            OutputStream mmOutStream = socket.getOutputStream();
            mBluetoothAdapter.cancelDiscovery();
            socket.connect();
            mmOutStream.write(toSend);
        } catch (Exception e) {
            Log.d("TAG", "Exception during write", e);
        }
    }

【问题讨论】:

  • 短信只能通过短信网关发送,不能通过蓝牙发送?
  • @Ryan,OP 在哪里提到他要发送短信?
  • 我想通过蓝牙发送它。哦,假设我想发送其他东西,但只能通过蓝牙发送。我成功获取了所有蓝牙设备名称和地址,现在我想发送一些东西到特定设备。
  • @user3243163 我的假设是text message 指的是短信,而不是包含短信以外的文本的文字消息。
  • @KanchaEkant 您是否从 BluetoothChat 示例应用程序中获得此代码?

标签: android bluetooth stream android-bluetooth


【解决方案1】:

如果您刚开始使用蓝牙 api,那么蓝牙聊天示例实际上是完美的选择。

假设您的应用程序仅使用一个 Activity,即 BluetoothChat 类:

要向您连接的设备发送文本,请使用 BluetoothChat 类中的“sendMessage(String message)”方法发送文本。

至于接收和处理文本,你会在 bluetoothchat 类的某处找到 handleMessage(Message msg) 方法,然后进入这部分:

case MESSAGE_READ:
            byte[] readBuf = (byte[]) msg.obj;
            // construct a string from the valid bytes in the buffer
            String readMessage = new String(readBuf, 0, msg.arg1);

看到 readMessage 字符串了吗?

这是您从其他设备收到的文本,现在您可以随意处理了。

然后只需更改 BluetoothChat 类引用的主布局,然后在 BluetoothChat 聊天中评论或删除有错误的部分,这些部分实际上将是您已删除或更改的 UI 中的部分。

我知道代码可能听起来很乱,但这是尽快使用它的最简单方法,并且观看视频教程或文本教程数小时只会让它变得更加复杂,相信我我之前尝试过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    相关资源
    最近更新 更多