【问题标题】:How to send a packet through Bluetooth to another Bluetooth enabled device如何通过蓝牙将数据包发送到另一个蓝牙设备
【发布时间】:2016-05-25 12:09:23
【问题描述】:

我正在开发一个 android 应用程序,它可以测量两个移动设备之间的距离。我已经能够获得附近启用 wifi 的设备的 rssi,然后我用它来粗略计算通常没有很高准确性的距离。为了提高准确性,我还想测量往返时间。

所以我的问题是,如果可能的话,如何通过蓝牙或 wifi 信号将数据包从一个 android 设备发送到另一个设备,然后接收响应?设备是否必须在每种情况下都进行配对,还是知道 MAC 地址就足够了?

【问题讨论】:

    标签: java android bluetooth distance


    【解决方案1】:

    快速谷歌搜索将引导您到 android 开发教程。 There 你应该找到问题的答案。但是总结一下:要通过蓝牙查找其他设备,您可以使用蓝牙适配器。在那里您可以尝试发现新的蓝牙设备或查询之前已连接到安卓设备的设备列表。

    发送数据包使用OutputStream.write() 读取InputStream.read()

    您将在开发站点上找到一个示例,但简而言之,它可能看起来像这样(教程中提供的示例的修改版本):

            InputStream is = null;
            OutputStream os = null;
     public ConnectedThread(BluetoothSocket socket) {
         try{
                is= socket.getInputStream();
                os = socket.getOutputStream();
            } catch (IOException e) { System.out.println(e); }
        }
    
        public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes=0; // bytes returned from read()
    
            // Keep listening to the InputStream until an exception occurs or the stream ends
            while (bytes != -1) {
                try {
                    // Read from the InputStream, the read bytes will be stored in the array
                    bytes = is.read(buffer); //reads 1024 bytes into the buffer
                } catch (IOException e) {
                    System.out.println(e);
                    break;
                }
            }
        }
    
        /* Call this from the main activity to send data to the remote device */
        public void write(byte[] bytes) {
            try {
                os.write(bytes);
            } catch (IOException e) { System.out.println(e); }
        }
    

    【讨论】:

    • 什么是mmInStream
    • @user924 应该是这样的输入流,我更正了。
    猜你喜欢
    • 2018-02-06
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    相关资源
    最近更新 更多