当前位置:   article > 正文

Android 蓝牙开发(一)

android 蓝牙开发

蓝牙简介

蓝牙(Bluetooth)是一种无线技术标准,能够在短距离内实现设备之间的数据交换和通信。蓝牙技术最初由瑞典爱立信公司于1994年开发,其名称源自丹麦国王哈拉尔·布吕特的译名“Harald Bluetooth”,他曾统一了斯堪的纳维亚半岛。

蓝牙技术是基于无线射频技术的,工作频率为2.4GHz,可支持多达8个设备同时连接。蓝牙技术应用广泛,包括手机、电脑、音频设备、手环、智能家居等领域,可以实现数据传输、音频传输、遥控和定位等功能。蓝牙技术的优点包括低功耗、低成本、易于使用和可靠性高等,成为了现代通信领域不可或缺的一部分。

前言

蓝牙是一种短距离无线通信技术,我们相对熟悉的移动端设备短距离通信技术有NFC红外蓝牙 ;

NFC:主要应用于操作简单,即时相应的刷卡

红外:主要应用于需要按键控制,例如家电遥控

蓝牙:主要用于两部设备之间复杂且大量的数据传输(这里又分为低功耗蓝牙经典蓝牙)今天小编给大家分享的是经典蓝牙

Android蓝牙开发步骤

1.检查设备是否支持蓝牙

在应用程序中,你需要首先检查设备是否支持蓝牙。你可以在AndroidManifest.xml文件中声明必需的蓝牙权限,并使用BluetoothAdapter类来查询设备是否支持蓝牙

  1. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  2. if (bluetoothAdapter == null) {
  3. // 该设备不支持蓝牙
  4. } else {
  5. // 该设备支持蓝牙
  6. }

2.打开蓝牙

在你的应用程序中,你需要引导用户打开他们的蓝牙功能。你可以使用ACTION_REQUEST_ENABLE活动提供一个请求

  1. if (!bluetoothAdapter.isEnabled()) {
  2. //如果该设备蓝牙未开启
  3. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  4. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  5. }

3.扫描可用蓝牙设备

一旦蓝牙已启用,你就可以开始扫描设备了。你可以使用BluetoothAdapter类和BluetoothDevice类执行扫描操作

bluetoothAdapter.startDiscovery();

可以使用BroadcastReceiver类来接收扫描结果:

  1. private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  2. public void onReceive(Context context, Intent intent) {
  3. String action = intent.getAction();
  4. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  5. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  6. //该设备成功搜索到蓝牙设备
  7. }
  8. }
  9. };

4.选择蓝牙并与其配对成功

通过BluetoothAdapter对象,你可以来进行蓝牙配对。你需要将BluetoothDevice类实例化并使用其connect()方法来建立连接

  1. BluetoothAdapter mBluetoothAdapter;
  2. BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  3. device.createBond();

 5.选择蓝牙并与其建立连接

通过BluetoothDevice对象,你可以使用BluetoothSocket类来建立蓝牙连接。你需要将BluetoothSocket类实例化并使用其connect()方法来建立连接

  1. BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
  2. socket.connect();

6.数据传输

一旦蓝牙连接已建立,你可以使用BluetoothSocket的getInputStream()和getOutputStream()方法来发送和接收数据

  1. InputStream inputStream = socket.getInputStream();
  2. OutputStream outputStream = socket.getOutputStream();

以上就是Android蓝牙开发的基本流程,需要注意的是在实际开发中,还需要处理蓝牙连接的断开、多设备连接等复杂情况

7.断开蓝牙连接并关闭蓝牙

  1. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  2. bluetoothAdapter.disable(); //关闭蓝牙

注意:Android提供了蓝牙模块的管理工具BluetoothAdapter(蓝牙适配器)

BluetoothAdapter类的一些常用方法说明:

1. enable() - 开启蓝牙

2. disable() - 关闭蓝牙

3. startDiscovery() - 开始搜索设备

4. cancelDiscovery() - 取消搜索设备

5. getBondedDevices() - 获取已配对的设备列表

6. getRemoteDevice(String address) - 获取远程设备对象

7. setState(int state) - 设置蓝牙状态

8. setScanMode(int mode) - 设置扫描模式

9. getScanMode() - 获取扫描模式

10. getName() - 获取本地蓝牙设备名称

11. setName(String name) - 设置本地蓝牙设备名称

12. getAddress() - 获取本地蓝牙设备地址

13. isDiscovering:判断是否正在搜索周围的蓝牙设备

14. getBluetoothLeScanner() - 获取BluetoothLeScanner对象

15. getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, int profile) - 获取BluetoothProfile对象

16. closeProfileProxy(int profile, BluetoothProfile proxy) - 关闭BluetoothProfile对象的连接

Android蓝牙开发效果演示

1. 声明蓝牙权限

新建一个Android项目,然后在AndroidManifest清单文件里声明相关的权限

2. 动态获取定位权限

  1. package com.example.bluetoothdemo;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.content.pm.PackageManager;
  6. import android.os.Bundle;
  7. public class MainActivity extends AppCompatActivity {
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.activity_main);
  12. //判断是否有访问位置的权限,没有权限,直接申请位置权限
  13. isPermission();
  14. }
  15. //动态获取位置权限
  16. @SuppressLint("NewApi")
  17. private void isPermission(){
  18. if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
  19. || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  20. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
  21. }
  22. }
  23. }

运行效果:

3. 判断该设备是否支持蓝牙功能

  1. package com.example.bluetoothdemo;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.bluetooth.BluetoothAdapter;
  6. import android.content.pm.PackageManager;
  7. import android.os.Bundle;
  8. import android.widget.Toast;
  9. public class MainActivity extends AppCompatActivity {
  10. private BluetoothAdapter mBluetoothAdapter;
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_main);
  15. //初始化蓝牙适配器
  16. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  17. if (isBluetoothSupport()){
  18. Toast.makeText(MainActivity.this, "该设备支持蓝牙功能", Toast.LENGTH_SHORT).show();
  19. }else {
  20. Toast.makeText(MainActivity.this, "该设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
  21. }
  22. }
  23. //判断该设备是否支持蓝牙功能
  24. private Boolean isBluetoothSupport(){
  25. if(mBluetoothAdapter == null){
  26. return false;
  27. }else {
  28. return true;
  29. }
  30. }
  31. }

运行效果:

4. 判断本机是否开启蓝牙

  1. package com.example.bluetoothdemo;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.bluetooth.BluetoothAdapter;
  6. import android.content.Intent;
  7. import android.content.pm.PackageManager;
  8. import android.os.Bundle;
  9. import android.widget.Toast;
  10. public class MainActivity extends AppCompatActivity {
  11. private BluetoothAdapter mBluetoothAdapter;
  12. @SuppressLint("MissingPermission")
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.activity_main);
  17. //初始化蓝牙适配器
  18. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  19. //判断蓝牙是否打开
  20. if(!isBluetoothEnabled()){
  21. //如果蓝牙未开启,则申请打开蓝牙
  22. Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  23. startActivityForResult(enableBluetoothIntent, RESULT_CANCELED);
  24. }else {
  25. }
  26. }
  27. /**
  28. * 检查该设备蓝牙是否开启
  29. */
  30. private boolean isBluetoothEnabled(){
  31. if(mBluetoothAdapter.isEnabled()){
  32. return true;
  33. }else {
  34. return false;
  35. }
  36. }
  37. @Override
  38. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  39. super.onActivityResult(requestCode, resultCode, data);
  40. if (requestCode == RESULT_CANCELED) {
  41. if (resultCode == RESULT_OK) {
  42. // 蓝牙已成功开启
  43. Toast.makeText(MainActivity.this, "用户已开启蓝牙", Toast.LENGTH_SHORT).show();
  44. } else {
  45. // 用户取消了蓝牙开启请求
  46. Toast.makeText(MainActivity.this, "用户已拒绝开启蓝牙", Toast.LENGTH_SHORT).show();
  47. }
  48. }
  49. }
  50. }

运行效果:

5. 获取设备已配对过的蓝牙设备

  1. package com.example.bluetoothdemo;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.bluetooth.BluetoothAdapter;
  6. import android.bluetooth.BluetoothDevice;
  7. import android.content.Intent;
  8. import android.content.pm.PackageManager;
  9. import android.os.Bundle;
  10. import android.util.Log;
  11. import android.widget.Toast;
  12. import java.util.Set;
  13. public class MainActivity extends AppCompatActivity {
  14. private BluetoothAdapter mBluetoothAdapter;
  15. @SuppressLint({"MissingPermission", "MissingInflatedId"})
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. //初始化蓝牙适配器
  21. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  22. //判断是否有访问位置的权限,没有权限,直接申请位置权限
  23. isPermission();
  24. getPairedDevices();
  25. }
  26. //动态获取位置权限
  27. @SuppressLint("NewApi")
  28. private void isPermission(){
  29. if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
  30. || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  31. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
  32. }
  33. }
  34. @SuppressLint("MissingPermission")
  35. private void getPairedDevices() {
  36. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  37. Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
  38. if (pairedDevices.size() > 0) {
  39. for (BluetoothDevice device : pairedDevices) {
  40. String deviceName = device.getName();
  41. String deviceHardwareAddress = device.getAddress();
  42. Log.d("MainActivity","设备名:"+deviceName+'\n'+"地址:"+deviceHardwareAddress);
  43. }
  44. }
  45. }
  46. }

运行效果:

6. 搜索蓝牙设备

  1. package com.example.bluetoothdemo;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.bluetooth.BluetoothAdapter;
  6. import android.bluetooth.BluetoothDevice;
  7. import android.content.BroadcastReceiver;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.content.IntentFilter;
  11. import android.content.pm.PackageManager;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.widget.Toast;
  15. import java.util.Set;
  16. public class MainActivity extends AppCompatActivity {
  17. private BluetoothAdapter mBluetoothAdapter;
  18. @SuppressLint({"MissingPermission", "MissingInflatedId"})
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.activity_main);
  23. //初始化蓝牙适配器
  24. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  25. //判断是否有访问位置的权限,没有权限,直接申请位置权限
  26. isPermission();
  27. mBluetoothAdapter.startDiscovery();
  28. registerBluetoothReceiver();
  29. }
  30. //动态获取位置权限
  31. @SuppressLint("NewApi")
  32. private void isPermission(){
  33. if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
  34. || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  35. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
  36. }
  37. }
  38. private void registerBluetoothReceiver(){
  39. //filter注册广播接收器
  40. IntentFilter filter = new IntentFilter();
  41. //蓝牙当前状态
  42. filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  43. //开始扫描蓝牙设备广播
  44. filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
  45. //找到蓝牙设备广播
  46. filter.addAction(BluetoothDevice.ACTION_FOUND);
  47. //扫描蓝牙设备结束广播
  48. filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  49. //蓝牙设备配对状态改变广播
  50. filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  51. //设备扫描模式改变广播
  52. filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
  53. registerReceiver(receiver, filter);
  54. }
  55. //处理找到蓝牙设备和搜索完成的广播消息
  56. BroadcastReceiver receiver = new BroadcastReceiver() {
  57. @SuppressLint("MissingPermission")
  58. @Override
  59. public void onReceive(Context context, Intent intent) {
  60. String action = intent.getAction();
  61. //开始查找设备
  62. if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
  63. Log.d("","开始查找");
  64. }
  65. //找到蓝牙设备
  66. else if(BluetoothDevice.ACTION_FOUND.equals(action)){
  67. //搜到蓝牙设备
  68. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  69. //把搜索到的设备添加到已找到列表中,显示它的信息
  70. Log.d("","设备名:"+device.getName()+'\n'+"地址:"+device.getAddress());
  71. }
  72. //查找设备结束
  73. else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
  74. //搜索完毕
  75. Toast.makeText(MainActivity.this, "选择要配对的蓝牙设备", Toast.LENGTH_SHORT).show();
  76. Log.d("","查找结束");
  77. }
  78. }
  79. };
  80. }

运行效果:

7. 配对蓝牙设备

  1. package com.example.bluetoothdemo;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.bluetooth.BluetoothAdapter;
  6. import android.bluetooth.BluetoothDevice;
  7. import android.content.BroadcastReceiver;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.content.IntentFilter;
  11. import android.content.pm.PackageManager;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.widget.Toast;
  15. import java.util.Set;
  16. public class MainActivity extends AppCompatActivity {
  17. private BluetoothAdapter mBluetoothAdapter;
  18. @SuppressLint({"MissingPermission", "MissingInflatedId"})
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.activity_main);
  23. //初始化蓝牙适配器
  24. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  25. //判断是否有访问位置的权限,没有权限,直接申请位置权限
  26. isPermission();
  27. getPairedDevices();
  28. }
  29. //动态获取位置权限
  30. @SuppressLint("NewApi")
  31. private void isPermission(){
  32. if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
  33. || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  34. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
  35. }
  36. }
  37. @SuppressLint("MissingPermission")
  38. private void getPairedDevices() {
  39. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  40. Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
  41. if (pairedDevices.size() > 0) {
  42. int i=0;
  43. for (BluetoothDevice device : pairedDevices) {
  44. i++;
  45. if(i==pairedDevices.size()){
  46. device.createBond();
  47. Log.d("","本机与另一个蓝牙设备"+device.getName()+"成功配对");
  48. }
  49. String deviceName = device.getName();
  50. String deviceHardwareAddress = device.getAddress();
  51. Log.d("","设备名:"+deviceName+'\n'+"地址:"+deviceHardwareAddress);
  52. }
  53. }
  54. }
  55. }

运行效果:

这一篇文章就先分享到这里,大家可以把代码复制一下去运行;下一篇再给大家分享一下蓝牙项目实战用法

Android蓝牙开发注意事项:

  1. 确保设备支持蓝牙:在开发之前,请确保您的设备支持蓝牙。大多数现代智能手机和平板电脑都支持蓝牙。

  2. 获取必要的权限:在开发蓝牙应用之前,您需要获取适当的权限。例如,您需要请求“android.permission.BLUETOOTH”权限,以便您的应用程序可以使用蓝牙。

  3. 确定您需要的蓝牙配置类型:Android提供了两种不同的蓝牙配置类型:经典蓝牙和低功耗蓝牙。使用低功耗蓝牙可以延长设备电池寿命,但需要Android 4.3(API level 18)或更高版本。

  4. 确保您的应用程序与其他应用程序兼容:在您的应用程序中使用蓝牙之前,请确保它与其他应用程序兼容。如果您的应用程序和其他应用程序同时使用蓝牙,可能会导致冲突和不稳定的行为。

  5. 使用正确的蓝牙协议:在开发蓝牙应用程序时,您需要确保使用正确的蓝牙协议。不同的设备和应用程序可能使用不同的蓝牙协议,因此您需要确定您的应用程序需要使用哪些协议。

  6. 处理错误和异常:在使用蓝牙时,可能会出现错误和异常。要确保您的应用程序具有适当的错误处理和异常处理代码,以确保它可以在出现问题时正确地处理蓝牙连接。

  7. 调试您的应用程序:在开发蓝牙应用程序时,请确保使用适当的调试工具。Android Studio提供了一些内置的调试工具,用于诊断和修复蓝牙连接问题。

  8. 避免使用已知的蓝牙错误:在使用蓝牙时,可能会出现许多已知的错误。要避免这些错误,请编写适当的代码,以确保您的应用程序可以正确处理这些错误。

需要注意的是,蓝牙开发需要特别注意电量和性能问题,对于频繁的蓝牙搜索、连接和数据传输等操作,应尽量减少或优化,避免对设备电量和性能造成过大的影响。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/549231
推荐阅读
相关标签
  

闽ICP备14008679号