二、搜索蓝牙并连接(安卓蓝牙ble教程)

短命女 2022-02-17 11:24 521阅读 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.content.pm.PackageManager;
  6. import android.os.Build;
  7. import android.os.Bundle;
  8. import android.support.v4.app.ActivityCompat;
  9. import android.support.v4.content.ContextCompat;
  10. import android.support.v7.app.AppCompatActivity;
  11. import android.util.Log;
  12. import android.view.View;
  13. import android.widget.Button;
  14. import android.widget.TextView;
  15. import android.widget.Toast;
  16. public class MainActivity extends AppCompatActivity {
  17. private BluetoothAdapter bluetoothAdapter;
  18. private Button btnCheckPermission;
  19. private TextView tvmsg;
  20. private Button btnSearchBLE;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25. getPermission(); //获取权限
  26. bluetoothInit(); //蓝牙初始化
  27. widgetInit(); //控件初始化
  28. widgetListener(); //控件监听
  29. }
  30. //获取权限
  31. private void getPermission() {
  32. //如果sdk版本大于23
  33. if (Build.VERSION.SDK_INT >=23){
  34. //如果没有权限
  35. if ((ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED))
  36. {
  37. //动态申请权限
  38. ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 10);
  39. }
  40. }
  41. }
  42. //控件初始化
  43. private void widgetInit() {
  44. //请自行提升到全局,原型是:Button startscan = findViewById(R.id.startscan);
  45. btnCheckPermission = findViewById(R.id.btnCheckPermission);
  46. //请自行提升到全局,原型是:TextView tvmsg = findViewById(R.id.tvmsg);
  47. tvmsg = findViewById(R.id.tvmsg);
  48. //请自行提升到全局,原型是:Button btnSearchBLE = findViewById(R.id.btnSearchBLE);
  49. btnSearchBLE = findViewById(R.id.btnSearchBLE);
  50. }
  51. //控件监听
  52. private void widgetListener() {
  53. //测试权限按钮监听
  54. btnCheckPermission.setOnClickListener(new View.OnClickListener() {
  55. @Override
  56. public void onClick(View v) {
  57. int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
  58. if (permissionCheck == PackageManager.PERMISSION_GRANTED) {//如果有权限
  59. Toast.makeText(MainActivity.this, "hava this permission", Toast.LENGTH_SHORT).show();//toast信息
  60. Log.d("权限:","有定位权限");//在logcat上打印信息
  61. tvmsg.setText("有定位权限");
  62. }else {
  63. getPermission();//获取权限
  64. Toast.makeText(MainActivity.this, "no this permission", Toast.LENGTH_SHORT).show();//toast信息
  65. Log.d("权限:","无定位权限");//在logcat上打印信息
  66. tvmsg.setText("无定位权限");
  67. }
  68. }
  69. });
  70. //搜索蓝牙按钮监听
  71. btnSearchBLE.setOnClickListener(new View.OnClickListener() {
  72. @Override
  73. public void onClick(View v) {
  74. //开始搜索蓝牙
  75. bluetoothAdapter.startLeScan(mBLEScanCallback);
  76. }
  77. });
  78. }
  79. //mBLEScanCallback回调函数
  80. private BluetoothAdapter.LeScanCallback mBLEScanCallback = new BluetoothAdapter.LeScanCallback() {
  81. @Override
  82. public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
  83. //打印蓝牙mac地址
  84. Log.d("BleMAC", device.getAddress());
  85. }
  86. };
  87. private void bluetoothInit() {
  88. //如果不支持蓝牙
  89. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
  90. {
  91. //提示不支持蓝牙
  92. Toast.makeText(this, "程序不支持该设备", Toast.LENGTH_SHORT).show();
  93. //退出程序
  94. finish();
  95. }
  96. //创建蓝牙适配器原型是BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  97. bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  98. //如果蓝牙适配器为空
  99. if (bluetoothAdapter == null)
  100. {
  101. //显示设备无蓝牙
  102. Toast.makeText(this, "设备无蓝牙", Toast.LENGTH_SHORT).show();
  103. //退出
  104. finish();
  105. }
  106. //如果蓝牙未开启
  107. if (!bluetoothAdapter.isEnabled())
  108. {
  109. //不提示,直接开启蓝牙
  110. bluetoothAdapter.enable();
  111. //提示开启蓝牙中
  112. Toast.makeText(this, "开启蓝牙中,如果未开启,请检查应用权限", Toast.LENGTH_SHORT).show();
  113. }
  114. }
  115. }

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

注:如果你照我上面这样写,十有八九是搜不到蓝牙信息的,为什么呢,需要打开手机定位服务才能搜索到

另一种解决办法,是在build.gradle中配置如下信息

  1. lintOptions {
  2. checkReleaseBuilds false
  3. abortOnError false
  4. }

以及修改build.gradle中的targetSdkVersion ,修改到20或21可以解决定位权限问题

具体配置如下

  1. apply plugin: 'com.android.application'
  2. android {
  3. lintOptions {
  4. checkReleaseBuilds false
  5. abortOnError false
  6. }
  7. compileSdkVersion 28
  8. defaultConfig {
  9. applicationId "club.stm32"
  10. minSdkVersion 18
  11. targetSdkVersion 21
  12. versionCode 1
  13. versionName "1.0"
  14. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  15. }
  16. buildTypes {
  17. release {
  18. minifyEnabled true
  19. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  20. }
  21. }
  22. }
  23. dependencies {
  24. implementation fileTree(dir: 'libs', include: ['*.jar'])
  25. implementation 'com.android.support:appcompat-v7:28.0.0'
  26. implementation 'com.android.support.constraint:constraint-layout:1.1.3'
  27. testImplementation 'junit:junit:4.12'
  28. androidTestImplementation 'com.android.support.test:runner:1.0.2'
  29. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
  30. }

发表评论

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

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

相关阅读

    相关 android BLE

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