如何将数据(字符串)发送到android中的配对设备?

如何将数据(字符串)发送到android中的配对设备?,第1张

概述我是第一次工作在蓝牙上.我得到了配对设备的列表.现在,我的要求是我需要向设备发送一些数据(字符串).我怎样才能做到这一点?我尝试搜索,但没有发现任何有用的信息.有人可以帮忙吗?解决方法:这样的事情可能就足够了:DataOutputStreamos;BluetoothAdapterbluetooth=BluetoothAda

我是第一次工作在蓝牙上.我得到了配对设备的列表.现在,我的要求是我需要向设备发送一些数据(字符串).我怎样才能做到这一点?我尝试搜索,但没有发现任何有用的信息.有人可以帮忙吗?

解决方法:

这样的事情可能就足够了:

DataOutputStream os;BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();broadcastReceiver discoveryResult = new broadcastReceiver() {    public voID onReceive(Context context, Intent intent) {        String remoteDevicename = intent.getStringExtra(BluetoothDevice.EXTRA_name);        BluetoothDevice remoteDevice;        remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);        Toast.makeText(getApplicationContext(), "discovered: " + remoteDevicename + " address " + remoteDevice.getAddress(), Toast.LENGTH_SHORT).show();        try{            BluetoothDevice device = bluetooth.getRemoteDevice(remoteDevice.getAddress());            Method m = device.getClass().getmethod("createRfcommSocket", new Class[] {int.class});            BluetoothSocket clIEntSocket =  (BluetoothSocket) m.invoke(device, 1);            clIEntSocket.connect();            os = new DataOutputStream(clIEntSocket.getoutputStream());            new clIEntSock().start();        } catch (Exception e) {            e.printstacktrace();            Log.e("BLUetoOTH", e.getMessage());        }    }};registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));bluetooth.enable();if (!bluetooth.isdiscovering()) {    bluetooth.startdiscovery();}public class clIEntSock extends Thread {    public voID run () {        try {            os.writeBytes("anything you want"); // anything you want            os.flush();        } catch (Exception e1) {            e1.printstacktrace();            return;        }    }}

您还将需要很多这样的导入:

import java.io.DatainputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.OutputStream;import java.lang.reflect.Method;import java.net.ServerSocket;import java.net.socket;import java.net.UnkNownHostException;import java.util.List;import java.util.UUID;import androID.os.Bundle;import androID.os.StrictMode;import androID.app.Activity;import androID.bluetooth.BluetoothAdapter;import androID.bluetooth.BluetoothDevice;import androID.bluetooth.BluetoothSocket;import androID.content.broadcastReceiver;import androID.content.Context;import androID.content.Intent;import androID.content.IntentFilter;import androID.util.Log;import androID.vIEw.Menu;import androID.Widget.Toast;

请注意,对于此示例代码,并非所有导入都是必需的,IDE可能会帮助您为您整理它们.

在os.writeBytes(“任何你想要的”)上传递数据; //任何您想要的行.

您还需要Permissions

总结

以上是内存溢出为你收集整理的如何将数据(字符串)发送到android中的配对设备?全部内容,希望文章能够帮你解决如何将数据(字符串)发送到android中的配对设备?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1095613.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存