Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >[Android实例] android 蓝牙开发浅析

[Android实例] android 蓝牙开发浅析

原创
作者头像
易寒
发布于 2021-12-21 06:27:09
发布于 2021-12-21 06:27:09
5430
举报
文章被收录于专栏:Android知识Android知识
  1. 使用蓝牙的响应权限<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  2. 配置本机蓝牙模块 在这里首先要了解对蓝牙操作一个核心类BluetoothAdapter
代码语言:txt
复制

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

//直接打开系统的蓝牙设置面板

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(intent, 0x1);

//直接打开蓝牙

adapter.enable();

//关闭蓝牙

adapter.disable();

//打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)

Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)

代码语言:txt
AI代码解释
复制
3.搜索蓝牙设备
使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备
startDiscovery()方法是一个异步方法,调用后会立即返回。该方法会进行对其他蓝牙设备的搜索,该过程会持续12秒。该方法调用后,搜索过程实际上是在一个System Service中进行的,所以可以调用cancelDiscovery()方法来停止搜索(该方法可以在未执行discovery请求时调用)。
请求Discovery后,系统开始搜索蓝牙设备,在这个过程中,系统会发送以下三个广播:
ACTION_DISCOVERY_START:开始搜索
ACTION_DISCOVERY_FINISHED:搜索结束
ACTION_FOUND:找到设备,这个Intent中包含两个extra fields:EXTRA_DEVICE和EXTRA_CLASS,分别包含BluetooDevice和BluetoothClass。
我们可以自己注册相应的BroadcastReceiver来接收响应的广播,以便实现某些功能

// 创建一个接收ACTION_FOUND广播的BroadcastReceiver

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

代码语言:txt
AI代码解释
复制
public void onReceive(Context context, Intent intent) {    
代码语言:txt
AI代码解释
复制
    String action = intent.getAction();    
代码语言:txt
AI代码解释
复制
    // 发现设备    
代码语言:txt
AI代码解释
复制
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {    
代码语言:txt
AI代码解释
复制
        // 从Intent中获取设备对象    
代码语言:txt
AI代码解释
复制
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);    
代码语言:txt
AI代码解释
复制
        // 将设备名称和地址放入array adapter,以便在ListView中显示    
代码语言:txt
AI代码解释
复制
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());     
代码语言:txt
AI代码解释
复制
    }     
代码语言:txt
AI代码解释
复制
}     

};

// 注册BroadcastReceiver

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

registerReceiver(mReceiver, filter); // 不要忘了之后解除绑定

代码语言:txt
AI代码解释
复制
4. 蓝牙Socket通信
如果打算建议两个蓝牙设备之间的连接,则必须实现服务器端与客户端的机制。当两个设备在同一个RFCOMM channel下分别拥有一个连接的BluetoothSocket,这两个设备才可以说是建立了连接。
服务器设备与客户端设备获取BluetoothSocket的途径是不同的。服务器设备是通过accepted一个incoming connection来获取的,而客户端设备则是通过打开一个到服务器的RFCOMM channel来获取的。

服务器端的实现
通过调用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)方法来获取BluetoothServerSocket(UUID用于客户端与服务器端之间的配对)
调用BluetoothServerSocket的accept()方法监听连接请求,如果收到请求,则返回一个BluetoothSocket实例(此方法为block方法,应置于新线程中)
如果不想在accept其他的连接,则调用BluetoothServerSocket的close()方法释放资源(调用该方法后,之前获得的BluetoothSocket实例并没有close。但由于RFCOMM一个时刻只允许在一条channel中有一个连接,则一般在accept一个连接后,便close掉BluetoothServerSocket)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 = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);    
    } catch (IOException 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) {     
            break;    
        }    

        // If a connection was accepted     
        if (socket != null) {   
            // Do work to manage the connection (in a separate thread)    
            manageConnectedSocket(socket);     
            mmServerSocket.close();     
            break;    
        }    
    }     
}      

/** Will cancel the listening socket, and cause the thread to finish */     
public void cancel() {     
    try {     
        mmServerSocket.close();     
    } catch (IOException e) { }     
}     }    客户端的实现
通过搜索得到服务器端的BluetoothService
调用BluetoothService的listenUsingRfcommWithServiceRecord(String, UUID)方法获取BluetoothSocket(该UUID应该同于服务器端的UUID)
调用BluetoothSocket的connect()方法(该方法为block方法),如果UUID同服务器端的UUID匹配,并且连接被服务器端accept,则connect()方法返回
注意:在调用connect()方法之前,应当确定当前没有搜索设备,否则连接会变得非常慢并且容易失败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;    



    // Get a BluetoothSocket to connect with the given BluetoothDevice    

    try {    

        // MY_UUID is the app's UUID string, also used by the server code    
        tmp = device.createRfcommSocketToServiceRecord(MY_UUID);    
    } catch (IOException e) { }     
    mmSocket = tmp;    
}    



public void run() {    
    // Cancel discovery because it will slow down the connection     
    mBluetoothAdapter.cancelDiscovery();    
    try {     
        // Connect the device through the socket. This will block     
        // until it succeeds or throws an exception     
        mmSocket.connect();     
    } catch (IOException connectException) {    

        // Unable to connect; close the socket and get out     
        try {     
            mmSocket.close();    
        } catch (IOException closeException) { }    
         return;    
    }    

      // Do work to manage the connection (in a separate thread)     
    manageConnectedSocket(mmSocket);     
}     

/** Will cancel an in-progress connection, and close the socket */    
 public void cancel() {    
    try {     
        mmSocket.close();    

    } catch (IOException e) { }    
 }     } 

4.连接管理(数据通信)

分别通过BluetoothSocket的getInputStream()和getOutputStream()方法获取InputStream和OutputStream

使用read(bytes[])和write(bytes[])方法分别进行读写操作

注意:read(bytes[])方法会一直block,知道从流中读取到信息,而write(bytes[])方法并不是经常的block(比如在另一设备没有及时read或者中间缓冲区已满的情况下,write方法会block)

代码语言:txt
AI代码解释
复制
private class ConnectedThread extends Thread {    
   
    private final BluetoothSocket mmSocket;    
   
    private final InputStream mmInStream;    
   
    private final OutputStream mmOutStream;    
   
    
   
    public ConnectedThread(BluetoothSocket socket) {    
   
        mmSocket = socket;    
   
        InputStream tmpIn = null;    
   
        OutputStream tmpOut = null;    
   
    
   
        // Get the input and output streams, using temp objects because    
   
        // member streams are final    
   
        try {    
   
            tmpIn = socket.getInputStream();    
   
            tmpOut = socket.getOutputStream();    
   
        } catch (IOException e) { }    
   
    
   
        mmInStream = tmpIn;    
   
        mmOutStream = tmpOut;    
   
    }    
   
    
   
    public void run() {    
   
        byte[] buffer = new byte[1024];  // buffer store for the stream    
   
        int bytes; // bytes returned from read()    
   
    
   
        // Keep listening to the InputStream until an exception occurs    
   
        while (true) {    
   
            try {    
   
                // Read from the InputStream    
   
                bytes = mmInStream.read(buffer);    
   
                // Send the obtained bytes to the UI Activity    
   
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)    
   
                        .sendToTarget();    
   
            } catch (IOException e) {    
   
                break;    
   
            }    
   
        }    
   
    }    
   
    
   
    /* Call this from the main Activity to send data to the remote device */    
   
    public void write(byte[] bytes) {    
   
        try {    
   
            mmOutStream.write(bytes);    
   
        } catch (IOException e) { }    
   
    }    
   
    
   
    /* Call this from the main Activity to shutdown the connection */    
   
    public void cancel() {    
   
        try {    
   
            mmSocket.close();    
   
        } catch (IOException e) { }    
   
    }    
   
}    

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Android 蓝牙操作
该BluetoothAdapter可以执行基本的蓝牙任务,例如启动设备发现,查询配对的设备列表,使用已知的MAC地址实例化一个BluetoothDevice类,并创建一个BluetoothServerSocket监听来自其他设备的连接请求
码客说
2019/10/22
1.5K0
Android 蓝牙开发(一)蓝牙通信「建议收藏」
<uses-permissionandroid:name=”android.permission.BLUETOOTH” />
全栈程序员站长
2022/09/14
4.2K0
Android 蓝牙开发(1)
Android 平台包含蓝牙网络堆栈支持,凭借此支持,设备能以无线方式与其他蓝牙设备交换数据。应用框架提供了通过 Android Bluetooth API 访问蓝牙功能的途径。使用 Bluetooth API Android 应用可以执行下面的操作:
开发者
2019/12/26
2.5K0
Android项目实战(二十六):蓝牙连接硬件设备开发规范流程
前言:   最近接触蓝牙开发,主要是通过蓝牙连接获取传感器硬件设备的数据,并进行处理。   网上学习一番,现整理出一套比较标准的 操作流程代码。   如果大家看得懂,将来只需要改下 硬件设备的MAC码 和 改下对接收数据的处理 即可。  一切都是套路~~~ 现在以一个小型项目需求来学习Android蓝牙编程 需求: 通过蓝牙获取硬件数据,并显示在一个随数据即时变化的动态折线图中。 实现思路: (1) 配对蓝牙设备   (2) 连接蓝牙设备    ,根据MAC地址,代码中修改 (3) 接收数据 (4) 处理数
听着music睡
2018/05/18
1.6K0
Android 蓝牙操作详解
1.启用蓝牙并使设备处于可发现状态        1.1 在使用BluetoothAdapter类的实例进操作之前,应启用isEnable()方法检查设备是否启用了蓝牙适配器。     // 使用意图提示用户启用蓝牙,并使设备处于可发现状态 private void startBluetooth() {           BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter(); // 检测蓝牙是否开启 if (!bt.isEnable
hbbliyong
2018/03/06
1.7K0
BlueTooth聊天软件(支持表情和语音)
1.三个用到的Thread的意义: (1)AcceptThread 服务器端,起监听作用。(accept函数) (2)ConnectThread This thread runs while attempting to make an outgoing connection with a device.(正在试图连接) (3)ConnectedThread This thread runs during a connection with a remote device. It handles all incoming and outgoing transmissions.(已经连接,准备进行数据交换)
提莫队长
2019/02/21
1.9K0
蓝牙串口通信控制Arduino全彩呼吸灯
HC-05 VCC ----- Arduino VIN HC-05 GND ----- Arduino GND HC-05 TXD ----- Arduino RXD HC-05 RXD ----- Arduino TXD
小雨coding
2020/06/09
2K0
蓝牙串口通信控制Arduino全彩呼吸灯
android开发之手机与单片机蓝牙模块通信
之前两篇都是在说与手机的连接,连接方法,和主动配对连接,都是手机与手机的操作,做起来还是没问题的,但是最终的目的是与单片机的蓝牙模块的通信。
全栈程序员站长
2022/03/11
8120
通过蓝牙实现安卓手机远程控制
本文将介绍如何通过蓝牙连接实现对安卓手机的远程控制。我们将探讨在安卓应用程序中设置蓝牙服务,以及如何使用Python编写一个蓝牙客户端,向手机发送命令,实现点击、滑动和返回等操作。通过该技术,你可以创建一个简单而强大的远程控制系统,方便在特定场景下控制手机操作。
测试开发囤货
2023/11/21
1.7K0
通过蓝牙实现安卓手机远程控制
Android在app中实现蓝牙服务Service的案例
在Android应用中,你可以通过服务(Service)来实现蓝牙数据读取。以下是一个简单的示例,演示如何创建一个Android服务以连接到蓝牙设备并读取数据。在实际应用中,你需要确保你的应用具备蓝牙权限,并使用合适的蓝牙库进行连接和数据读取。
丹牛Daniel
2023/10/17
1.2K0
android开发之蓝牙主动配对连接手机
上一篇介绍了手机配对连接的三种方式,这篇以完整的一个代码实例介绍如何搜索周围的蓝牙设备,以及主动配对,连接。
全栈程序员站长
2022/03/11
7510
android开发之蓝牙配对连接的方法「建议收藏」
最近在做蓝牙开锁的小项目,手机去连接单片机总是出现问题,和手机的连接也不稳定,看了不少蓝牙方面的文档,做了个关于蓝牙连接的小结。
全栈程序员站长
2022/03/11
3.9K0
蓝牙API介绍及基本功能实现
通过监听BluetoothAdapter.ACTION_STATE_CHANGED监听蓝牙状态的改变
fanfan
2022/05/07
1.5K0
【Android 应用开发】BluetoothDevice详解
该类实现了Parcelable接口, 实现了Parcelable接口的类的对象可以封装到Parcel对象中, 封装后的数据可以通过Intent或者IPC传递;
韩曙亮
2023/03/27
1.9K0
Android蓝牙开发(二)之蓝牙配对和蓝牙连接
上篇文章:https://blog.csdn.net/huangliniqng/article/details/82185983
黄林晴
2019/01/10
4.4K0
蓝牙门禁Android客户端
 先来了解下Android传统蓝牙连接的大致简单的流程: 其中涉及到几个类依次来介绍,废话不多说,下面是从Android4.4开发指南蓝牙所用到的类的截图: 第一个类BluetoothAdapter:
用户1148881
2018/01/17
2K0
蓝牙门禁Android客户端
android 十八 蓝牙及Wi-Fi
蓝牙是一种重要的短距离无线通信技术,它被广泛应用于各种设备,比如计算机、手机、汽车等,支持设备之间的近距离通信,从而是数据传输更加快捷有效。Wi-Fi是一种高速的无线通信协议,它具有传输速度高,传输距离长的特点。通过WiFi,手机、PDA、电脑等移动设备可以以无线方式连接网络。本节中我们主要来学习Android开发中如何调用系统中蓝牙以及wifi的功能。
用户9184480
2024/12/17
1100
android 十八 蓝牙及Wi-Fi
相关推荐
Android 蓝牙操作
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文