三、筛选蓝牙信息并连接(安卓蓝牙ble教程)

╰+攻爆jí腚メ 2022-02-15 12:26 500阅读 0赞

1、MainActivity.java

注:如果复制代码进项目时显示红色,请按ALT+ENTER键导包(import class)

  1. package club.stm32;
  2. import android.Manifest;
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothDevice;
  5. import android.bluetooth.BluetoothGatt;
  6. import android.bluetooth.BluetoothGattCallback;
  7. import android.content.pm.PackageManager;
  8. import android.os.Build;
  9. import android.os.Bundle;
  10. import android.support.v4.app.ActivityCompat;
  11. import android.support.v4.content.ContextCompat;
  12. import android.support.v7.app.AppCompatActivity;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.widget.Button;
  16. import android.widget.TextView;
  17. import android.widget.Toast;
  18. public class MainActivity extends AppCompatActivity {
  19. /**
  20. * 需要根据条件修改的参数
  21. */
  22. private String MacHeader = "A6:C0:80"; //蓝牙的Mac地址前六位,需要根据自己的蓝牙进行修改
  23. private BluetoothAdapter bluetoothAdapter;
  24. private Button btnCheckPermission;
  25. private TextView tvmsg;
  26. private Button btnSearchBLE;
  27. private BluetoothDevice mdevice;
  28. private BluetoothGatt bluetoothGatt;
  29. @Override
  30. protected void onCreate(Bundle savedInstanceState) {
  31. super.onCreate(savedInstanceState);
  32. setContentView(R.layout.activity_main);
  33. getPermission(); //获取权限
  34. bluetoothInit(); //蓝牙初始化
  35. widgetInit(); //控件初始化
  36. widgetListener(); //控件监听
  37. }
  38. //获取权限
  39. private void getPermission() {
  40. //如果sdk版本大于23
  41. if (Build.VERSION.SDK_INT >=23){
  42. //如果没有权限
  43. if ((ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED))
  44. {
  45. //动态申请权限
  46. ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 10);
  47. }
  48. }
  49. }
  50. //控件初始化
  51. private void widgetInit() {
  52. //请自行提升到全局,原型是:Button startscan = findViewById(R.id.startscan);
  53. btnCheckPermission = findViewById(R.id.btnCheckPermission);
  54. //请自行提升到全局,原型是:TextView tvmsg = findViewById(R.id.tvmsg);
  55. tvmsg = findViewById(R.id.tvmsg);
  56. //请自行提升到全局,原型是:Button btnSearchBLE = findViewById(R.id.btnSearchBLE);
  57. btnSearchBLE = findViewById(R.id.btnSearchBLE);
  58. }
  59. //控件监听
  60. private void widgetListener() {
  61. //测试权限按钮监听
  62. btnCheckPermission.setOnClickListener(new View.OnClickListener() {
  63. @Override
  64. public void onClick(View v) {
  65. int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
  66. if (permissionCheck == PackageManager.PERMISSION_GRANTED) {//如果有权限
  67. Toast.makeText(MainActivity.this, "hava this permission", Toast.LENGTH_SHORT).show();//toast信息
  68. Log.d("权限:","有定位权限");//在logcat上打印信息
  69. tvmsg.setText("有定位权限");
  70. }else {
  71. getPermission();//获取权限
  72. Toast.makeText(MainActivity.this, "no this permission", Toast.LENGTH_SHORT).show();//toast信息
  73. Log.d("权限:","无定位权限");//在logcat上打印信息
  74. tvmsg.setText("无定位权限");
  75. }
  76. }
  77. });
  78. //搜索蓝牙按钮监听
  79. btnSearchBLE.setOnClickListener(new View.OnClickListener() {
  80. @Override
  81. public void onClick(View v) {
  82. //开始搜索蓝牙
  83. bluetoothAdapter.startLeScan(mBLEScanCallback);
  84. }
  85. });
  86. }
  87. //mBLEScanCallback回调函数
  88. private BluetoothAdapter.LeScanCallback mBLEScanCallback = new BluetoothAdapter.LeScanCallback() {
  89. @Override
  90. public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
  91. //打印蓝牙mac地址
  92. Log.d("BleMAC", device.getAddress());
  93. if(device.toString().indexOf(MacHeader) == 0){
  94. Log.d("符合的蓝牙地址", device.getAddress());
  95. bluetoothAdapter.stopLeScan(mBLEScanCallback);
  96. //停止搜索蓝牙,降低功耗
  97. bluetoothAdapter.stopLeScan(mBLEScanCallback);
  98. //获取远程设备(连接蓝牙)原型是BluetoothDevice mdevice = bluetoothAdapter.getRemoteDevice(des);请自行提升全局
  99. mdevice = bluetoothAdapter.getRemoteDevice(device.toString());
  100. //连接bluetoothGatt 到这一步时,蓝牙已经连接上了
  101. //原型是BluetoothGatt bluetoothGatt = device.connectGatt(MainActivity.this, false, bluetoothGattCallback); 请自行提升全局
  102. //bluetoothGattCallback是蓝牙gatt回调函数,接下来会跳到bluetoothGattCallback函数
  103. bluetoothGatt = mdevice.connectGatt(MainActivity.this, false, bluetoothGattCallback);
  104. Log.d("已连接到蓝牙", device.getAddress());
  105. }
  106. }
  107. };
  108. //蓝牙回调函数
  109. private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
  110. };
  111. private void bluetoothInit() {
  112. //如果不支持蓝牙
  113. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
  114. {
  115. //提示不支持蓝牙
  116. Toast.makeText(this, "程序不支持该设备", Toast.LENGTH_SHORT).show();
  117. //退出程序
  118. finish();
  119. }
  120. //创建蓝牙适配器原型是BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  121. bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  122. //如果蓝牙适配器为空
  123. if (bluetoothAdapter == null)
  124. {
  125. //显示设备无蓝牙
  126. Toast.makeText(this, "设备无蓝牙", Toast.LENGTH_SHORT).show();
  127. //退出
  128. finish();
  129. }
  130. //如果蓝牙未开启
  131. if (!bluetoothAdapter.isEnabled())
  132. {
  133. //不提示,直接开启蓝牙
  134. bluetoothAdapter.enable();
  135. //提示开启蓝牙中
  136. Toast.makeText(this, "开启蓝牙中,如果未开启,请检查应用权限", Toast.LENGTH_SHORT).show();
  137. }
  138. }
  139. }

2、布局文件activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:orientation="vertical"
  8. tools:context=".MainActivity">
  9. <TextView
  10. android:layout_width="match_parent"
  11. android:layout_height="300dp"
  12. android:text="Hello World!"
  13. android:id="@+id/tvmsg"
  14. app:layout_constraintBottom_toBottomOf="parent"
  15. app:layout_constraintLeft_toLeftOf="parent"
  16. app:layout_constraintRight_toRightOf="parent"
  17. app:layout_constraintTop_toTopOf="parent" />
  18. <LinearLayout
  19. android:orientation="horizontal"
  20. android:layout_width="match_parent"
  21. android:layout_height="wrap_content">
  22. <Button
  23. android:layout_weight="1"
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:text="测试权限"
  27. android:id="@+id/btnCheckPermission"
  28. />
  29. <Button
  30. android:layout_weight="1"
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:text="搜索蓝牙"
  34. android:id="@+id/btnSearchBLE"
  35. />
  36. </LinearLayout>
  37. </LinearLayout>

效果图:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MjM0MDg3_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,500人围观)

还没有评论,来说两句吧...

相关阅读

    相关 android BLE

    直接上代码吧,完整的程序代码如下: 首先是MainActivity,本段代码完成了子模转换和保存数据的功能,并将要发送的数据整理成了和作者的小伙伴说好的格式。需要注意的是,