每日速讯:什么是蓝牙Android平台?如何设置蓝牙?
什么是蓝牙
Android 平台包含蓝牙网络堆栈支持,此支持能让设备以无线方式与其他蓝牙设备交换数据。应用框架提供通过 Android Bluetooth API 访问蓝牙功能的权限。这些 API 允许应用以无线方式连接到其他蓝牙设备,从而实现点到点和多点无线功能。
【资料图】
Android 应用可通过 Bluetooth API 执行以下操作:
扫描其他蓝牙设备查询本地蓝牙适配器的配对蓝牙设备建立 RFCOMM 通道通过服务发现连接到其他设备与其他设备进行双向数据传输管理多个连接
蓝牙权限
如要在应用中使用蓝牙功能,必须声明两个权限。第一个是 BLUETOOTH。第二个是 ACCESS_FINE_LOCATION。
设置蓝牙
1.获取
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (bluetoothAdapter == null) {// Device doesn"t support Bluetooth}
2.启用
if (!bluetoothAdapter.isEnabled()) {Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}
查找设备
1.查询已配对的设备
SetpairedDevices = bluetoothAdapter.getBondedDevices();if (pairedDevices.size() > 0) {// There are paired devices. Get the name and address of each paired device. for (BluetoothDevice device : pairedDevices) {String deviceName = device.getName(); String deviceHardwareAddress = device.getAddress(); // MAC address }}
2.发现设备
@Overrideprotected void onCreate(Bundle savedInstanceState) {... // Register for broadcasts when a device is discovered. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, filter);}// Create a BroadcastReceiver for ACTION_FOUND.private final BroadcastReceiver receiver = new BroadcastReceiver() {public void onReceive(Context context, Intent intent) {String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) {// Discovery has found a device. Get the BluetoothDevice // object and its info from the Intent. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String deviceName = device.getName(); String deviceHardwareAddress = device.getAddress(); // MAC address } }};@Overrideprotected void onDestroy() {super.onDestroy(); ... // Don"t forget to unregister the ACTION_FOUND receiver. unregisterReceiver(receiver);}
连接设备
private class AcceptThread extends Thread {private final BluetoothServerSocket mmServerSocket; public AcceptThread() {// Use a temporary object that is later assigned to mmServerSocket // because mmServerSocket is final. BluetoothServerSocket tmp = null; try {// MY_UUID is the app"s UUID string, also used by the client code. tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID); } catch (IOException e) {Log.e(TAG, "Socket"s listen() method failed", e); } mmServerSocket = tmp; } public void run() {BluetoothSocket socket = null; // Keep listening until exception occurs or a socket is returned. while (true) {try {socket = mmServerSocket.accept(); } catch (IOException e) {Log.e(TAG, "Socket"s accept() method failed", e); break; } if (socket != null) {// A connection was accepted. Perform work associated with // the connection in a separate thread. manageMyConnectedSocket(socket); mmServerSocket.close(); break; } } } // Closes the connect socket and causes the thread to finish. public void cancel() {try {mmServerSocket.close(); } catch (IOException e) {Log.e(TAG, "Could not close the connect socket", e); } }}
服务端代码
class AcceptThread extends Thread {private BluetoothServerSocket mServerSocket; private BluetoothSocket mSocket; private InputStream btIs; private OutputStream btOs; private PrintWriter writer; private boolean canAccept; private boolean canRecv; public AcceptThread() {canAccept = true; canRecv = true; } @Override public void run() {try {//获取套接字 BluetoothServerSocket temp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("TEST", UUID.fromString(BT_UUID)); mServerSocket = temp; //监听连接请求 -- 作为测试,只允许连接一个设备 if (mServerSocket != null) {// while (canAccept) {mSocket = mServerSocket.accept();//阻塞等待客户端连接 sendHandlerMsg("有客户端连接"); // } } //获取输入输出流 btIs = mSocket.getInputStream(); btOs = mSocket.getOutputStream(); //通讯-接收消息 BufferedReader reader = new BufferedReader(new InputStreamReader(btIs, "UTF-8")); String content = null; while (canRecv) {content = reader.readLine(); sendHandlerMsg("收到消息:" + content); } } catch (IOException e) {e.printStackTrace(); } finally {try {if (mSocket != null) {mSocket.close(); } // btIs.close();//两个输出流都依赖socket,关闭socket即可 // btOs.close(); } catch (IOException e) {e.printStackTrace(); sendHandlerMsg("错误:" + e.getMessage()); } } } private void sendHandlerMsg(String content) {Message msg = mHandler.obtainMessage(); msg.what = 1001; msg.obj = content; mHandler.sendMessage(msg); } public void write(String msg) {if (btOs != null) {try {if (writer == null) {writer = new PrintWriter(new OutputStreamWriter(btOs, "UTF-8"), true); } writer.println(msg); } catch (UnsupportedEncodingException e) {e.printStackTrace(); writer.close(); sendHandlerMsg("错误:" + e.getMessage()); } } } }
客户端代码
private class ConnectThread extends Thread {private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) {// Use a temporary object that is later assigned to mmSocket // because mmSocket is final. BluetoothSocket tmp = null; mmDevice = device; try {// Get a BluetoothSocket to connect with the given BluetoothDevice. // MY_UUID is the app"s UUID string, also used in the server code. tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) {Log.e(TAG, "Socket"s create() method failed", e); } mmSocket = tmp; } public void run() {// Cancel discovery because it otherwise slows down the connection. bluetoothAdapter.cancelDiscovery(); try {// Connect to the remote device through the socket. This call blocks // until it succeeds or throws an exception. mmSocket.connect(); } catch (IOException connectException) {// Unable to connect; close the socket and return. try {mmSocket.close(); } catch (IOException closeException) {Log.e(TAG, "Could not close the client socket", closeException); } return; } // The connection attempt succeeded. Perform work associated with // the connection in a separate thread. manageMyConnectedSocket(mmSocket); } // Closes the client socket and causes the thread to finish. public void cancel() {try {mmSocket.close(); } catch (IOException e) {Log.e(TAG, "Could not close the client socket", e); } }}
运行截图
标签:
相关推荐:
最新新闻:
- 【科普】什么是通信网络?计算机网络的演进
- 怎么用免费dede采集插件让网站快速收录?有关企业网站优化诊断的三个方面
- 每日速讯:什么是蓝牙Android平台?如何设置蓝牙?
- 吊扇调速器怎么工作?吊扇调速器的原理介绍
- 环球视讯!Bil站自动完成任务工具——BilibiliTask
- 戴尔台式机怎么设置U盘启动?戴尔台式机U盘启动的设置方法
- 忘记TP-LINK路由器登录密码如何解决?TP-LINK路由器登录密码找回方法
- 智能手机与智能机有什么区别?关于智能机的区别介绍
- Windows键是键盘上的哪个键?Win键的作用有多大?
- 实时焦点:压阻式压力传感器/压力变送器的类型有哪些?压力传感器/压力变送器的类型
- media/sf_Share/LED系统命令介绍 Linux系统介绍-焦点短讯
- 【环球播资讯】跟女人聊天的秘诀是什么?会说话的男人到底有哪些特质?
- BT是什么?BT(BitTorren比特流)的原理及使用方法_环球观焦点
- 网速慢到底是电信问题还是电脑问题?网速评判谁更可靠?|焦点热文
- 视网膜显示屏和普通显示屏什么区别?看完你就明白了-全球独家
- 摄像录音笔都有哪些品牌?韩国现代品牌的摄像笔有什么特点?:焦点速讯
- 3米的棉麻面料怎么做?下摆裹身连衣裙的裁剪制作教程 环球精选
- 联想掌上电脑多少钱?联想掌上电脑价格及推荐
- 全球信息:redPacketPay.php:扫二维码领红包系统软件开发流程
- kali中如何下载帝国?Web安全攻防之帝国_播资讯
- 公交车到底什么时候能够到站?GPS接受器价格一览_今日聚焦
- 诺基亚7230怎样刷机?诺基亚7230刷机步骤盘点|最新快讯
- 3d基本走势图:彩宝贝 辽宁快乐12选5开奖结果-速看
- 分布式集群化设计——MySQLServer
- 阿里云香港云服务器有哪些优势?阿里云香港服务器购买教程
- 天天即时看!guest账户怎么开启和关闭?guest账户关闭和开启教程
- 液晶屏幕显示器整机无电故障如何处理?液晶屏幕维修之常见问题判断
- 2-5阶魔方玩法:四阶魔方降阶法的还原步骤
- 【可编程】直流电源供应器与负载之间串联一只二极管
- 世界新动态:论坛会员颜小风:ThatPhoto超牛的图像编辑器
- 全球资讯:12306上可以提前多少天买火车票?12306车票的有效期的规定
- 世界即时看!电梯楼层控制系统——IC卡电梯门禁系统介绍
- 诺基亚6700c评测:全金刚材质打造的全金属手机
- 一系列C++类库——PocAny+库
- 环球快报:广州干细胞实验室建设:洁净空调选择有哪些事项?
- 快资讯丨Desktop.ini是什么文件?desktop.ini可以删除吗?
- mac电脑网游加速器哪个好用?网易uu加速器Mac版推荐
- 苹果手机怎么设置屏幕旋转?苹果手机屏幕旋转的设置教程 世界动态
- 【威航软件园】免费的windows文件搜索工具_天天快资讯
- 今日关注:西门子cx6怎么样?西门子cx65详细评测
- 如何制作鼠标跟随效果?鼠标跟随效果制作教程|环球热头条
- 诺基亚手机怎么恢复出厂设置?方法步骤
- 三星s5660如何刷机?三星s5660刷机教程
- 电脑怎么重装系统?电脑重装系统方法大全
- 环球观点:贴片0603蓝光led启动电压2.5V 已经开始导通
- 国企的面试我们应该怎么准备?国企面试的注意事项
- 微软:一旦收购成功 PS版COD甚至比Xbox版还好-环球时讯
- 4V4对战游戏《古惑狼大乱斗》6月20日上市
- 像素动作游戏《双雄编年史:天照之怒》确定发售日
- 秋的声音仿写句子_秋的声音仿写-视讯
- 百亿补贴 Bose蓝牙音箱814元
- 2023爱普生创新大会开启共绘“多彩世界”新篇章
- 【环球时快讯】迷你主机腰斩价!655元买了不亏
- 环球观速讯丨3月21日基金净值:诺安双利债券发起最新净值2.66,涨0.38%
- COSPLAY图赏:俄妹COS《哈利波特》赫敏 泳装版意外惊艳 天天信息
- 今日关注:即时战略《异形:坠入黑暗》公布 6月20日发售
- 汇顶科技创新方案组合助力联想拯救者Y900高能体验_每日消息
- 性能狂飙 高能体验 联想拯救者2023全线生态新品强势发布_热资讯
- C宏源(301246):第三届第二十四次董事会会议决议,审议《关于签订募集资金三方及四监管协议的议案》等议案
- 国外流行起的新种族“星之种” 认为自己是外星人_每日视讯
- 外网热议:为何《光环》改编剧没像《美末》一样成功
- 《星球大战绝地:幸存者》新截图公开
- 环球观热点:《雷霆沙赞2》主演想拍第三部:希望能大战丧尸!
- “最丑超模”获泰国2023选美冠军引热议:评委口太重|环球新视野
- Win11更新修复了复制慢问题 但有可能降低SSD性能:当前消息
- 当前动态:透明外壳:红魔8 Pro银翼版首销 4999元
- 起亚官宣:正式进军中国电动汽车领域-天天快资讯
- 比亚迪:4月上市智能手表-快播
- 《死亡搁浅》玛玛演员新写真 五官精致眼神灵动 天天观热点
- 《暗黑4》公测宣传片:你只管玩游戏 家务活我搞定
- 【焦点热闻】《生化危机4:重制版》角色介绍:商人和光明教主
- 银保监会将开展保险机构销售人员互联网营销宣传合规性自查整改工作:天天精选
- 795元,零刻EQ12迷你主机上市,搭载英特尔12代Alder Lake
- 数据挖掘者爆料:《COD19》三名人气角色将可操作
- 印度风烹饪《Venba》宣布首日XGP:做份电子咖喱 世界热闻