├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── drawable
│ │ │ │ ├── rect_round_button_ripple.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ └── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── top
│ │ │ └── gtf35
│ │ │ └── bleserial
│ │ │ ├── MainActivity.java
│ │ │ └── BLESPPUtils.java
│ ├── test
│ │ └── java
│ │ │ └── top
│ │ │ └── gtf35
│ │ │ └── bleserial
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── top
│ │ └── gtf35
│ │ └── bleserial
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── vcs.xml
├── runConfigurations.xml
├── gradle.xml
├── misc.xml
└── codeStyles
│ └── Project.xml
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── readme.md
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name='BLESerial'
2 | include ':app'
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BLESerial
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gtf35/BLESerial/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #F97ABD9A
4 | #F97ABD9A
5 | #F97ABD9A
6 |
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat May 16 19:59:14 CST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/top/gtf35/bleserial/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package top.gtf35.bleserial;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/rect_round_button_ripple.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | -
6 |
8 |
9 |
11 |
12 |
13 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | 1.8
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 29
5 | buildToolsVersion "29.0.3"
6 |
7 | defaultConfig {
8 | applicationId "top.gtf35.bleserial"
9 | minSdkVersion 22
10 | targetSdkVersion 29
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 | implementation 'androidx.appcompat:appcompat:1.1.0'
29 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
30 | }
31 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/top/gtf35/bleserial/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package top.gtf35.bleserial;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("top.gtf35.bleserial", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
25 |
26 |
31 |
32 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
22 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | 蓝牙工具类:```BLESPPUtils.java``` [直达链接](https://github.com/gtf35/BLESerial/blob/master/app/src/main/java/top/gtf35/bleserial/BLESPPUtils.java)
2 |
3 | 调用示例:MainActivity.java [直达链接](https://github.com/gtf35/BLESerial/blob/master/app/src/main/java/top/gtf35/bleserial/MainActivity.java)
4 |
5 | 配套讲解文章:快速上手 Android 蓝牙串口 SPP 开发 [直达链接](https://blog.gtf35.top/bluetooth_spp/)
6 |
7 | 使用方式:
8 |
9 | - 1 加入权限并确认处理好运行时权限,已经授予了定位权限(用于扫描蓝牙设备)
10 |
11 | ```xml
12 |
13 |
14 |
15 |
16 |
17 |
18 | ```
19 |
20 | - 2 实例化工具类,第一个参数是 context,可以为任意 context,不涉及 UI 操作;第二个参数是「蓝牙活动回调」
21 |
22 | ```java
23 | // 初始化
24 | mBLESPPUtils = new BLESPPUtils(MainActivity.this, new BLESPPUtils.OnBluetoothAction() {
25 | /**
26 | * 当发现新设备
27 | *
28 | * @param device 设备
29 | */
30 | @Override
31 | public void onFoundDevice(BluetoothDevice device) {
32 |
33 | }
34 |
35 | /**
36 | * 当连接成功
37 | *
38 | * @param device
39 | */
40 | @Override
41 | public void onConnectSuccess(BluetoothDevice device) {
42 |
43 | }
44 |
45 | /**
46 | * 当连接失败
47 | *
48 | * @param msg 失败信息
49 | */
50 | @Override
51 | public void onConnectFailed(String msg) {
52 |
53 | }
54 |
55 | /**
56 | * 当接收到 byte 数组
57 | *
58 | * @param bytes 内容
59 | */
60 | @Override
61 | public void onReceiveBytes(byte[] bytes) {
62 |
63 | }
64 |
65 | /**
66 | * 当调用接口发送了 byte 数组
67 | *
68 | * @param bytes 内容
69 | */
70 | @Override
71 | public void onSendBytes(byte[] bytes) {
72 |
73 | }
74 |
75 | /**
76 | * 当结束搜索设备
77 | */
78 | @Override
79 | public void onFinishFoundDevice() {
80 |
81 | }
82 | });
83 | ```
84 |
85 | - 3 设置接收停止标志位字符串
86 |
87 | ```java
88 | mBLESPPUtils.setStopString("\r\n");
89 | ```
90 |
91 | - 4 启用工具类
92 |
93 | ```java
94 | mBLESPPUtils.onCreate();
95 | ```
96 |
97 | - 5 在适当的时候销毁工具类,譬如 Activity 的 ```onDestroy()```
98 |
99 | ```java
100 | @Override
101 | protected void onDestroy() {
102 | super.onDestroy();
103 | mBLESPPUtils.onDestroy();
104 | }
105 | ```
106 |
107 | - 6 检查蓝牙开启情况
108 |
109 | ```java
110 | // 用户没有开启蓝牙的话打开蓝牙
111 | if (!mBLESPPUtils.isBluetoothEnable()) mBLESPPUtils.enableBluetooth();
112 | ```
113 |
114 | - 7 搜索蓝牙设备,搜索结果在上面的回调里了
115 |
116 | ```java
117 | mBLESPPUtils.startDiscovery();
118 | ```
119 |
120 | - 8 使用搜索到的 BluetoothDevice 连接设备
121 |
122 | ```java
123 | mBLESPPUtils.connect(bluetoothDevice);
124 | ```
125 |
126 | - 9 使用之前保存的 MAC 地址连接
127 |
128 | ```java
129 | mBLESPPUtils.connect("mac地址");
130 | ```
131 |
132 | - 10 发送 byte 数组到串口
133 |
134 | ```java
135 | mBLESPPUtils.send("hello\r\n".getBytes());
136 | ```
137 |
138 | - 11 接收到串口发送的 byte 数组在上面第二步的```onReceiveBytes(byte[] bytes)```回调中
139 |
140 | - 12 启用工具类日志输出
141 |
142 | ```java
143 | mBLESPPUtils.enableBluetooth();
144 | ```
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | xmlns:android
14 |
15 | ^$
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | xmlns:.*
25 |
26 | ^$
27 |
28 |
29 | BY_NAME
30 |
31 |
32 |
33 |
34 |
35 |
36 | .*:id
37 |
38 | http://schemas.android.com/apk/res/android
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 | .*:name
48 |
49 | http://schemas.android.com/apk/res/android
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | name
59 |
60 | ^$
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 | style
70 |
71 | ^$
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 | .*
81 |
82 | ^$
83 |
84 |
85 | BY_NAME
86 |
87 |
88 |
89 |
90 |
91 |
92 | .*
93 |
94 | http://schemas.android.com/apk/res/android
95 |
96 |
97 | ANDROID_ATTRIBUTE_ORDER
98 |
99 |
100 |
101 |
102 |
103 |
104 | .*
105 |
106 | .*
107 |
108 |
109 | BY_NAME
110 |
111 |
112 |
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/top/gtf35/bleserial/MainActivity.java:
--------------------------------------------------------------------------------
1 | package top.gtf35.bleserial;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.bluetooth.BluetoothDevice;
5 | import android.content.Context;
6 | import android.graphics.Color;
7 | import android.os.Bundle;
8 | import android.util.Log;
9 | import android.view.View;
10 | import android.widget.EditText;
11 | import android.widget.FrameLayout;
12 | import android.widget.LinearLayout;
13 | import android.widget.ProgressBar;
14 | import android.widget.ScrollView;
15 | import android.widget.TextView;
16 | import android.widget.Toast;
17 |
18 | import androidx.appcompat.app.AlertDialog;
19 | import androidx.appcompat.app.AppCompatActivity;
20 | import androidx.core.app.ActivityCompat;
21 | import androidx.core.content.ContextCompat;
22 |
23 | import java.util.ArrayList;
24 |
25 | public class MainActivity extends AppCompatActivity implements BLESPPUtils.OnBluetoothAction, View.OnClickListener {
26 | // 蓝牙工具
27 | private BLESPPUtils mBLESPPUtils;
28 | // 保存搜索到的设备,避免重复
29 | private ArrayList mDevicesList = new ArrayList<>();
30 | // 对话框控制
31 | private DeviceDialogCtrl mDeviceDialogCtrl;
32 | // log 视图
33 | private TextView mLogTv;
34 | // 输入的 ET
35 | private EditText mInputET;
36 |
37 | @Override
38 | protected void onCreate(Bundle savedInstanceState) {
39 | super.onCreate(savedInstanceState);
40 | setContentView(R.layout.activity_main);
41 | // 申请权限
42 | initPermissions();
43 | // 绑定视图
44 | findViewById(R.id.btn_send).setOnClickListener(this);
45 | mLogTv = findViewById(R.id.tv_log);
46 | mInputET = findViewById(R.id.ed_input);
47 |
48 | // 初始化
49 | mBLESPPUtils = new BLESPPUtils(this, this);
50 | // 启用日志输出
51 | mBLESPPUtils.enableBluetooth();
52 | // 设置接收停止标志位字符串
53 | mBLESPPUtils.setStopString("\r\n");
54 | // 用户没有开启蓝牙的话打开蓝牙
55 | if (!mBLESPPUtils.isBluetoothEnable()) mBLESPPUtils.enableBluetooth();
56 | // 启动工具类
57 | mBLESPPUtils.onCreate();
58 |
59 | mDeviceDialogCtrl = new DeviceDialogCtrl(this);
60 | mDeviceDialogCtrl.show();
61 | }
62 |
63 | @Override
64 | protected void onDestroy() {
65 | super.onDestroy();
66 | mBLESPPUtils.onDestroy();
67 | }
68 |
69 | /**
70 | * 申请运行时权限,不授予会搜索不到设备
71 | */
72 | private void initPermissions() {
73 | if (ContextCompat.checkSelfPermission(this, "android.permission-group.LOCATION") != 0) {
74 | ActivityCompat.requestPermissions(
75 | this,
76 | new String[]{
77 | "android.permission.ACCESS_FINE_LOCATION",
78 | "android.permission.ACCESS_COARSE_LOCATION",
79 | "android.permission.ACCESS_WIFI_STATE"},
80 | 1
81 | );
82 | }
83 | }
84 |
85 | /**
86 | * 当发现新设备
87 | *
88 | * @param device 设备
89 | */
90 | @Override
91 | public void onFoundDevice(BluetoothDevice device) {
92 | Log.d("BLE", "发现设备 " + device.getName() + device.getAddress());
93 | // 判断是不是重复的
94 | for (int i = 0; i < mDevicesList.size(); i++) {
95 | if (mDevicesList.get(i).getAddress().equals(device.getAddress())) return;
96 | }
97 | // 添加,下次有就不显示了
98 | mDevicesList.add(device);
99 | // 添加条目到 UI 并设置点击事件
100 | mDeviceDialogCtrl.addDevice(device, new View.OnClickListener() {
101 | @SuppressLint("SetTextI18n")
102 | @Override
103 | public void onClick(View v) {
104 | BluetoothDevice clickDevice = (BluetoothDevice) v.getTag();
105 | postShowToast("开始连接:" + clickDevice.getName());
106 | mLogTv.setText(mLogTv.getText() + "\n" + "开始连接:" + clickDevice.getName());
107 | mBLESPPUtils.connect(clickDevice);
108 | }
109 | });
110 | }
111 |
112 | /**
113 | * 当连接成功
114 | *
115 | * @param device 设备
116 | */
117 | @Override
118 | public void onConnectSuccess(final BluetoothDevice device) {
119 | postShowToast("连接成功", new DoSthAfterPost() {
120 | @SuppressLint("SetTextI18n")
121 | @Override
122 | public void doIt() {
123 | mLogTv.setText(
124 | mLogTv.getText() + "\n连接成功:" + device.getName() + " | " + device.getAddress()
125 | );
126 | mDeviceDialogCtrl.dismiss();
127 | }
128 | });
129 | }
130 |
131 | /**
132 | * 当连接失败
133 | *
134 | * @param msg 失败信息
135 | */
136 | @Override
137 | public void onConnectFailed(final String msg) {
138 | postShowToast("连接失败:" + msg, new DoSthAfterPost() {
139 | @SuppressLint("SetTextI18n")
140 | @Override
141 | public void doIt() {
142 | mLogTv.setText(mLogTv.getText() + "\n连接失败:" + msg);
143 | }
144 | });
145 | }
146 |
147 | /**
148 | * 当接收到 byte 数组
149 | *
150 | * @param bytes 内容
151 | */
152 | @Override
153 | public void onReceiveBytes(final byte[] bytes) {
154 | postShowToast("收到数据:" + new String(bytes), new DoSthAfterPost() {
155 | @SuppressLint("SetTextI18n")
156 | @Override
157 | public void doIt() {
158 | mLogTv.setText(mLogTv.getText() + "\n收到数据:" + new String(bytes));
159 | }
160 | });
161 | }
162 |
163 | /**
164 | * 当调用接口发送 byte 数组
165 | *
166 | * @param bytes 内容
167 | */
168 | @Override
169 | public void onSendBytes(final byte[] bytes) {
170 | postShowToast("发送数据:" + new String(bytes), new DoSthAfterPost() {
171 | @SuppressLint("SetTextI18n")
172 | @Override
173 | public void doIt() {
174 | mLogTv.setText(mLogTv.getText() + "\n发送数据:" + new String(bytes));
175 | }
176 | });
177 | }
178 |
179 | /**
180 | * 当结束搜索设备
181 | */
182 | @Override
183 | public void onFinishFoundDevice() { }
184 |
185 | /**
186 | * 按钮的点击事件
187 | *
188 | * @param v 点击的按钮
189 | */
190 | @Override
191 | public void onClick(View v) {
192 | if (v.getId() == R.id.btn_send) {
193 | mBLESPPUtils.send((mInputET.getText().toString() + "\n").getBytes());
194 | }
195 | }
196 |
197 | /**
198 | * 设备选择对话框控制
199 | */
200 | private class DeviceDialogCtrl {
201 | private LinearLayout mDialogRootView;
202 | private ProgressBar mProgressBar;
203 | private AlertDialog mConnectDeviceDialog;
204 |
205 | DeviceDialogCtrl(Context context) {
206 | // 搜索进度条
207 | mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
208 | mProgressBar.setLayoutParams(
209 | new LinearLayout.LayoutParams(
210 | LinearLayout.LayoutParams.MATCH_PARENT,
211 | 50
212 | )
213 | );
214 |
215 | // 根布局
216 | mDialogRootView = new LinearLayout(context);
217 | mDialogRootView.setOrientation(LinearLayout.VERTICAL);
218 | mDialogRootView.addView(mProgressBar);
219 | mDialogRootView.setMinimumHeight(700);
220 |
221 | // 容器布局
222 | ScrollView scrollView = new ScrollView(context);
223 | scrollView.addView(mDialogRootView,
224 | new FrameLayout.LayoutParams(
225 | FrameLayout.LayoutParams.MATCH_PARENT,
226 | 700
227 | )
228 | );
229 |
230 | // 构建对话框
231 | mConnectDeviceDialog = new AlertDialog
232 | .Builder(context)
233 | .setNegativeButton("刷新", null)
234 | .setPositiveButton("退出", null)
235 | .create();
236 | mConnectDeviceDialog.setTitle("选择连接的蓝牙设备");
237 | mConnectDeviceDialog.setView(scrollView);
238 | mConnectDeviceDialog.setCancelable(false);
239 | }
240 |
241 | /**
242 | * 显示并开始搜索设备
243 | */
244 | void show() {
245 | mBLESPPUtils.startDiscovery();
246 | mConnectDeviceDialog.show();
247 | mConnectDeviceDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnLongClickListener(new View.OnLongClickListener() {
248 | @Override
249 | public boolean onLongClick(View v) {
250 | mConnectDeviceDialog.dismiss();
251 | return false;
252 | }
253 | });
254 | mConnectDeviceDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
255 | @Override
256 | public void onClick(View v) {
257 | mConnectDeviceDialog.dismiss();
258 | finish();
259 | }
260 | });
261 | mConnectDeviceDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
262 | @Override
263 | public void onClick(View v) {
264 | mDialogRootView.removeAllViews();
265 | mDialogRootView.addView(mProgressBar);
266 | mDevicesList.clear();
267 | mBLESPPUtils.startDiscovery();
268 | }
269 | });
270 | }
271 |
272 | /**
273 | * 取消对话框
274 | */
275 | void dismiss() {
276 | mConnectDeviceDialog.dismiss();
277 | }
278 |
279 | /**
280 | * 添加一个设备到列表
281 | * @param device 设备
282 | * @param onClickListener 点击回调
283 | */
284 | private void addDevice(final BluetoothDevice device, final View.OnClickListener onClickListener) {
285 | runOnUiThread(new Runnable() {
286 | @SuppressLint("SetTextI18n")
287 | @Override
288 | public void run() {
289 | TextView devTag = new TextView(MainActivity.this);
290 | devTag.setClickable(true);
291 | devTag.setPadding(20,20,20,20);
292 | devTag.setBackgroundResource(R.drawable.rect_round_button_ripple);
293 | devTag.setText(device.getName() + "\nMAC:" + device.getAddress());
294 | devTag.setTextColor(Color.WHITE);
295 | devTag.setOnClickListener(onClickListener);
296 | devTag.setTag(device);
297 | devTag.setLayoutParams(
298 | new LinearLayout.LayoutParams(
299 | LinearLayout.LayoutParams.MATCH_PARENT,
300 | LinearLayout.LayoutParams.WRAP_CONTENT
301 | )
302 | );
303 | ((LinearLayout.LayoutParams) devTag.getLayoutParams()).setMargins(
304 | 20, 20, 20, 20);
305 | mDialogRootView.addView(devTag);
306 | }
307 | });
308 | }
309 | }
310 |
311 | /**
312 | * 在主线程弹出 Toast
313 | *
314 | * @param msg 信息
315 | */
316 | private void postShowToast(final String msg) {
317 | postShowToast(msg, null);
318 | }
319 |
320 | /**
321 | * 在主线程弹出 Toast
322 | *
323 | * @param msg 信息
324 | * @param doSthAfterPost 在弹出后做点什么
325 | */
326 | private void postShowToast(final String msg, final DoSthAfterPost doSthAfterPost) {
327 | runOnUiThread(new Runnable() {
328 | @Override
329 | public void run() {
330 | Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
331 | if (doSthAfterPost != null) doSthAfterPost.doIt();
332 | }
333 | });
334 | }
335 |
336 | private interface DoSthAfterPost {
337 | void doIt();
338 | }
339 |
340 | }
341 |
--------------------------------------------------------------------------------
/app/src/main/java/top/gtf35/bleserial/BLESPPUtils.java:
--------------------------------------------------------------------------------
1 | package top.gtf35.bleserial;
2 |
3 | import android.bluetooth.BluetoothAdapter;
4 | import android.bluetooth.BluetoothDevice;
5 | import android.bluetooth.BluetoothSocket;
6 | import android.content.BroadcastReceiver;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.content.IntentFilter;
10 | import android.os.AsyncTask;
11 | import android.util.Log;
12 |
13 | import java.io.IOException;
14 | import java.io.InputStream;
15 | import java.util.Formatter;
16 | import java.util.UUID;
17 |
18 |
19 | /**
20 | * 蓝牙工具类 2020/5/18
21 | * 功能:搜索蓝牙设备
22 | * 连接蓝牙串口
23 | * 发送串口数据
24 | * 接收串口数据
25 | * @author gtf35 gtf@gtf35.top
26 | */
27 | class BLESPPUtils {
28 | private static boolean mEnableLogOut = false;
29 | private Context mContext;
30 | private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
31 | private OnBluetoothAction mOnBluetoothAction;
32 | private ConnectTask mConnectTask = new ConnectTask();
33 |
34 | /**
35 | * 搜索到新设备广播广播接收器
36 | */
37 | private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
38 | public void onReceive(Context context, Intent intent) {
39 | String action = intent.getAction();
40 | if (BluetoothDevice.ACTION_FOUND.equals(action)) {
41 | BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
42 | if (mOnBluetoothAction != null) mOnBluetoothAction.onFoundDevice(device);
43 | }
44 | }
45 | };
46 |
47 | /**
48 | * 搜索结束广播接收器
49 | */
50 | private final BroadcastReceiver mFinishFoundReceiver = new BroadcastReceiver() {
51 | public void onReceive(Context context, Intent intent) {
52 | String action = intent.getAction();
53 | if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
54 | if (mOnBluetoothAction != null) mOnBluetoothAction.onFinishFoundDevice();
55 | }
56 | }
57 | };
58 |
59 | /**
60 | * 连接任务
61 | */
62 | private static class ConnectTask extends AsyncTask {
63 | private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
64 | BluetoothSocket bluetoothSocket;
65 | BluetoothDevice romoteDevice;
66 | OnBluetoothAction onBluetoothAction;
67 | boolean isRunning = false;
68 | String stopString = "\r\n";
69 |
70 | @Override
71 | protected Void doInBackground(String... bluetoothDevicesMac) {
72 | // 记录标志位,开始运行
73 | isRunning = true;
74 |
75 | // 尝试获取 bluetoothSocket
76 | try {
77 | UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
78 | romoteDevice = bluetoothAdapter.getRemoteDevice(bluetoothDevicesMac[0]);
79 | bluetoothSocket = romoteDevice.createRfcommSocketToServiceRecord(SPP_UUID);
80 | } catch (Exception e) {
81 | logD("获取Socket失败");
82 | isRunning = false;
83 | e.printStackTrace();
84 | return null;
85 | }
86 |
87 | // 检查有没有获取到
88 | if (bluetoothSocket == null) {
89 | onBluetoothAction.onConnectFailed("连接失败:获取Socket失败");
90 | isRunning = false;
91 | return null;
92 | }
93 |
94 | // 尝试连接
95 | try {
96 | // 等待连接,会阻塞线程
97 | bluetoothSocket.connect();
98 | logD( "连接成功");
99 | onBluetoothAction.onConnectSuccess(romoteDevice);
100 | } catch (Exception connectException) {
101 | connectException.printStackTrace();
102 | logD("连接失败:" + connectException.getMessage());
103 | onBluetoothAction.onConnectFailed("连接失败:" + connectException.getMessage());
104 | return null;
105 | }
106 |
107 | // 开始监听数据接收
108 | try {
109 | InputStream inputStream = bluetoothSocket.getInputStream();
110 | byte[] result = new byte[0];
111 | while (isRunning) {
112 | logD("looping");
113 | byte[] buffer = new byte[256];
114 | // 等待有数据
115 | while (inputStream.available() == 0 && isRunning) {if (System.currentTimeMillis() < 0) break;}
116 | while (isRunning) {
117 | try {
118 | int num = inputStream.read(buffer);
119 | byte[] temp = new byte[result.length + num];
120 | System.arraycopy(result, 0, temp, 0, result.length);
121 | System.arraycopy(buffer, 0, temp, result.length, num);
122 | result = temp;
123 | if (inputStream.available() == 0) break;
124 | } catch (Exception e) {
125 | e.printStackTrace();
126 | onBluetoothAction.onConnectFailed("接收数据单次失败:" + e.getMessage());
127 | break;
128 | }
129 | }
130 | try {
131 | // 返回数据
132 | logD("当前累计收到的数据=>" + byte2Hex(result));
133 | byte[] stopFlag = stopString.getBytes();
134 | int stopFlagSize = stopFlag.length;
135 | boolean shouldCallOnReceiveBytes = false;
136 | logD("标志位为:" + byte2Hex(stopFlag));
137 | for (int i = stopFlagSize - 1; i >= 0; i--) {
138 | int indexInResult = result.length - (stopFlagSize - i);
139 | if (indexInResult >= result.length || indexInResult < 0) {
140 | shouldCallOnReceiveBytes = false;
141 | logD("收到的数据比停止字符串短");
142 | break;
143 | }
144 | if (stopFlag[i] == result[indexInResult]) {
145 | logD("发现" + byte2Hex(stopFlag[i]) + "等于" + byte2Hex(result[indexInResult]));
146 | shouldCallOnReceiveBytes = true;
147 | } else {
148 | logD("发现" + byte2Hex(stopFlag[i]) + "不等于" + byte2Hex(result[indexInResult]));
149 | shouldCallOnReceiveBytes = false;
150 | }
151 | }
152 | if (shouldCallOnReceiveBytes) {
153 | onBluetoothAction.onReceiveBytes(result);
154 | // 清空
155 | result = new byte[0];
156 | }
157 | } catch (Exception e) {
158 | e.printStackTrace();
159 | onBluetoothAction.onConnectFailed("验证收到数据结束标志出错:" + e.getMessage());
160 | }
161 | }
162 | } catch (Exception e) {
163 | e.printStackTrace();
164 | onBluetoothAction.onConnectFailed("接收数据失败:" + e.getMessage());
165 | }
166 | return null;
167 | }
168 |
169 | @Override
170 | protected void onCancelled() {
171 | try {
172 | logD("AsyncTask 开始释放资源");
173 | isRunning = false;
174 | bluetoothSocket.close();
175 | } catch (IOException e) {
176 | e.printStackTrace();
177 | }
178 | }
179 |
180 | /**
181 | * 发送
182 | *
183 | * @param msg 内容
184 | */
185 | void send(byte[] msg) {
186 | try {
187 | bluetoothSocket.getOutputStream().write(msg);
188 | onBluetoothAction.onSendBytes(msg);
189 | } catch (Exception e){e.printStackTrace();}
190 | }
191 | }
192 |
193 | /**
194 | * 设置停止标志位字符串
195 | *
196 | * @param stopString 停止位字符串
197 | */
198 | @SuppressWarnings("SameParameterValue")
199 | void setStopString(String stopString) {
200 | mConnectTask.stopString = stopString;
201 | }
202 |
203 | /**
204 | * 蓝牙活动回调
205 | */
206 | public interface OnBluetoothAction {
207 | /**
208 | * 当发现新设备
209 | * @param device 设备
210 | */
211 | void onFoundDevice(BluetoothDevice device);
212 |
213 | /**
214 | * 当连接成功
215 | */
216 | void onConnectSuccess(BluetoothDevice device);
217 |
218 | /**
219 | * 当连接失败
220 | * @param msg 失败信息
221 | */
222 | void onConnectFailed(String msg);
223 |
224 | /**
225 | * 当接收到 byte 数组
226 | * @param bytes 内容
227 | */
228 | void onReceiveBytes(byte[] bytes);
229 |
230 | /**
231 | * 当调用接口发送了 byte 数组
232 | * @param bytes 内容
233 | */
234 | void onSendBytes(byte[] bytes);
235 |
236 | /**
237 | * 当结束搜索设备
238 | */
239 | void onFinishFoundDevice();
240 | }
241 |
242 | /**
243 | * 构造蓝牙工具
244 | *
245 | * @param context 上下文
246 | * @param onBluetoothAction 蓝牙状态改变回调
247 | */
248 | BLESPPUtils(Context context, OnBluetoothAction onBluetoothAction) {
249 | mContext = context;
250 | mOnBluetoothAction = onBluetoothAction;
251 | }
252 |
253 | /**
254 | * 初始化
255 | */
256 | void onCreate() {
257 | IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
258 | mContext.registerReceiver(mReceiver, foundFilter);
259 | IntentFilter finishFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
260 | mContext.registerReceiver(mFinishFoundReceiver, finishFilter);
261 | }
262 |
263 | /**
264 | * 销毁,释放资源
265 | */
266 | void onDestroy() {
267 | try {
268 | logD("onDestroy,开始释放资源");
269 | mConnectTask.isRunning = false;
270 | mConnectTask.cancel(true);
271 | mContext.unregisterReceiver(mReceiver);
272 | mContext.unregisterReceiver(mFinishFoundReceiver);
273 | } catch (Exception e) {e.printStackTrace();}
274 | }
275 |
276 | /**
277 | * 开始搜索
278 | */
279 | void startDiscovery() {
280 | if (mBluetoothAdapter.isDiscovering()) mBluetoothAdapter.cancelDiscovery();
281 | mBluetoothAdapter.startDiscovery();
282 | }
283 |
284 | /**
285 | * 使用搜索到的数据连接
286 | *
287 | * @param device 设备
288 | */
289 | void connect(BluetoothDevice device) {
290 | mBluetoothAdapter.cancelDiscovery();
291 | connect(device.getAddress());
292 | }
293 |
294 | /**
295 | * 使用Mac地址来连接
296 | *
297 | * @param deviceMac 要连接的设备的 MAC
298 | */
299 | private void connect(String deviceMac) {
300 | if (mConnectTask.getStatus() == AsyncTask.Status.RUNNING && mConnectTask.isRunning) {
301 | if (mOnBluetoothAction != null) mOnBluetoothAction.onConnectFailed("有正在连接的任务");
302 | return;
303 | }
304 | mConnectTask.onBluetoothAction = mOnBluetoothAction;
305 | try {
306 | mConnectTask.execute(deviceMac);
307 | } catch (Exception e) {e.printStackTrace();}
308 | }
309 |
310 | /**
311 | * 发送 byte 数组到串口
312 | *
313 | * @param bytes 要发送的数据
314 | */
315 | void send(byte[] bytes) {
316 | if (mConnectTask != null) mConnectTask.send(bytes);
317 | }
318 |
319 | /**
320 | * 获取用户是否打开了蓝牙
321 | */
322 | boolean isBluetoothEnable() {
323 | return mBluetoothAdapter.isEnabled();
324 | }
325 |
326 | /**
327 | * 开启蓝牙
328 | */
329 | void enableBluetooth() {
330 | mBluetoothAdapter.enable();
331 | }
332 |
333 | /**
334 | * 字节转换为 16 进制字符串
335 | *
336 | * @param b 字节
337 | * @return Hex 字符串
338 | */
339 | private static String byte2Hex(byte b) {
340 | StringBuilder hex = new StringBuilder(Integer.toHexString(b));
341 | if (hex.length() > 2) {
342 | hex = new StringBuilder(hex.substring(hex.length() - 2));
343 | }
344 | while (hex.length() < 2) {
345 | hex.insert(0, "0");
346 | }
347 | return hex.toString();
348 | }
349 |
350 |
351 | /**
352 | * 字节数组转换为 16 进制字符串
353 | *
354 | * @param bytes 字节数组
355 | * @return Hex 字符串
356 | */
357 | private static String byte2Hex(byte[] bytes) {
358 | Formatter formatter = new Formatter();
359 | for (byte b : bytes) {
360 | formatter.format("%02x", b);
361 | }
362 | String hash = formatter.toString();
363 | formatter.close();
364 | return hash;
365 | }
366 |
367 | /**
368 | * 启用日志输出
369 | */
370 | @SuppressWarnings("unused")
371 | static void setEnableLogOut() {
372 | mEnableLogOut = true;
373 | }
374 |
375 | /**
376 | * 打印日志
377 | */
378 | private static void logD(String msg) {
379 | if (mEnableLogOut)Log.d("BLEUTILS", msg);
380 | }
381 | }
382 |
--------------------------------------------------------------------------------