getPairedDevices();
24 |
25 | void scan(ScanConfig scanConfig, ScanResultListener scanResultListener);
26 |
27 | void stopSearch();
28 |
29 | void connect(BluetoothDevice device, ConnectResultlistner connectResultlistner);
30 | void destory();
31 | void pin(BluetoothDevice device, PinResultListener resultListener);
32 | void cancelPin(BluetoothDevice device, ResultListener resultListener);
33 | void setServerConnectResultListener(ConnectResultlistner connectResultListener);
34 | void registerServerConnection(ConnectResultlistner connectResultListener);
35 |
36 | void setForegroundService(boolean foregroundService);
37 | void setNotification(Notification notification);
38 | void enableDiscoverable(long time);
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/listener/BluetoothPermissionCallBack.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.listener;
2 |
3 | /**
4 | * @author AllenLiu
5 | * @version 1.0
6 | * @date 2019/5/27
7 |
8 | */
9 | public interface BluetoothPermissionCallBack {
10 | void onBlueToothEnabled();
11 | void permissionFailed();
12 | }
13 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/listener/ConnectResultlistner.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.listener;
2 |
3 | import android.os.Parcel;
4 | import android.os.Parcelable;
5 | import com.allenliu.classicbt.CLog;
6 | import com.allenliu.classicbt.Connect;
7 |
8 | import java.io.Serializable;
9 |
10 | /**
11 | * @author AllenLiu
12 | * @version 1.0
13 | * @date 2019/5/8
14 |
15 | */
16 | public interface ConnectResultlistner {
17 |
18 | void connectSuccess(Connect connect);
19 |
20 | void connectFailed(Exception e);
21 | void disconnected();
22 |
23 |
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/listener/DeviceSelectListener.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.listener;
2 |
3 | import android.bluetooth.BluetoothDevice;
4 |
5 | /**
6 | * @author AllenLiu
7 | * @version 1.0
8 | * @date 2019/5/8
9 |
10 | */
11 | public interface DeviceSelectListener {
12 | void onDeviceSelected(BluetoothDevice bluetoothDevice);
13 | }
14 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/listener/PacketDefineListener.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.listener;
2 |
3 | /**
4 | * @author AllenLiu
5 | * @date 2019/8/26
6 | */
7 | public interface PacketDefineListener {
8 | byte[] getPacketStart();
9 |
10 | byte[] getPacketEnd();
11 | }
12 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/listener/PinResultListener.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.listener;
2 |
3 | import android.bluetooth.BluetoothDevice;
4 |
5 | /**
6 | * author : AllenLiu
7 |
8 | * date : 2019/5/10 4:59 PM
9 | * desc :
10 | */
11 | public interface PinResultListener {
12 | default void startPair(BluetoothDevice device){}
13 | default void pairing(BluetoothDevice device){}
14 | void paired(BluetoothDevice device);
15 | default void pairFailed(BluetoothDevice device){}
16 | }
17 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/listener/ResultListener.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.listener;
2 |
3 | /**
4 | * author : AllenLiu
5 |
6 | * date : 2019/5/10 4:43 PM
7 | * desc :
8 | */
9 | public interface ResultListener {
10 | void success();
11 | void failed(Exception e);
12 | }
13 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/listener/ScanResultListener.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.listener;
2 |
3 | import android.bluetooth.BluetoothDevice;
4 |
5 | public interface ScanResultListener {
6 | void onDeviceFound(BluetoothDevice device);
7 |
8 | void onFinish();
9 |
10 | void onError();
11 | }
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/listener/TransferProgressListener.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.listener;
2 |
3 | /**
4 | * author : AllenLiu
5 | * date : 2019/5/10 5:49 PM
6 | * desc :
7 | */
8 | public interface TransferProgressListener {
9 | void transfering(int progress);
10 | void transferSuccess(byte[] bytes);
11 | void transferFailed(Exception exception);
12 |
13 |
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/scan/ScanConfig.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.scan;
2 |
3 | /**
4 | * @author AllenLiu
5 | * @version 1.0
6 | * @date 2019/5/8
7 |
8 | */
9 | public class ScanConfig {
10 | private long scanTime;
11 |
12 | public ScanConfig(long scanTime) {
13 | this.scanTime = scanTime;
14 | }
15 |
16 | public long getScanTime() {
17 | return scanTime;
18 | }
19 |
20 | public void setScanTime(long scanTime) {
21 | this.scanTime = scanTime;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/classicbt/src/main/java/com/allenliu/classicbt/scan/ScanTimer.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt.scan;
2 |
3 | import android.os.CountDownTimer;
4 |
5 | /**
6 | * @author AllenLiu
7 | * @version 1.0
8 | * @date 2019/5/8
9 |
10 | */
11 | public class ScanTimer extends CountDownTimer {
12 |
13 | public ScanTimer(ScanConfig config) {
14 | super(config.getScanTime(), 1000);
15 | }
16 |
17 | @Override
18 | public void onTick(long millisUntilFinished) {
19 |
20 | }
21 |
22 | @Override
23 | public void onFinish() {
24 |
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/classicbt/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | classicbt
3 | 提示
4 | 使用蓝牙功能需要定位权限
5 | 取消
6 | 设置
7 | 蓝牙传输服务正在运行
8 | 蓝牙服务
9 |
10 |
--------------------------------------------------------------------------------
/classicbt/src/test/java/com/allenliu/classicbt/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.allenliu.classicbt;
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 | }
--------------------------------------------------------------------------------
/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 | # Kotlin code style for this project: "official" or "obsolete":
15 | kotlin.code.style=official
16 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AlexLiuSheng/EasyBluetoothFrame/43b7a1678189befceb28d49e57535fd3e8bb67bb/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon May 20 10:05:52 CST 2019
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.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | ## EasyBluetoothFrame
23 | 这是一个适用于经典蓝牙通讯的快速开发框架。
24 |
25 |
26 |
27 |
28 |
29 | ### 框架适用范围
30 | 本框架只适用于支持蓝牙3.0协议的设备进行数据连接传输,也就是通常说的经典蓝牙,通常手机与手机之间的连接都属于经典蓝牙模式范畴,而一般连接外设耳机等设备,大多
31 | 属于BLE蓝牙(低功耗蓝牙),这两种蓝牙除了名字有相同之外,通信方式、原理、协议完全不一样。
32 |
33 | ### 导入
34 | > **version=**[](https://jitpack.io/#AlexLiuSheng/EasyBluetoothFrame)
35 | ```
36 | allprojects {
37 | repositories {
38 | maven { url "https://jitpack.io" }
39 | }
40 | }
41 | dependencies {
42 | implementation 'com.github.AlexLiuSheng:EasyBluetoothFrame:version'
43 | }
44 |
45 | ```
46 | ### 蓝牙连接流程
47 | ---
48 | 经典蓝牙采用C/S模式,所以同一个设备,只能作为Client端或者Server端的其中一个,
49 | - 如果设备充当Server端,那么监听流程如下:
50 | - 蓝牙权限获取
51 | - 设置设备可被发现
52 | - 设置监听UUID
53 | - 注册为Server
54 | - 等待配对、连接、传输数据
55 |
56 | - 如果设备充当Client,本框架蓝牙的连接流程一般为:
57 | - 蓝牙权限获取
58 | - 扫描设备
59 | - 配对、绑定设备
60 | - 建立连接
61 | - 传输数据
62 |
63 |
64 | ### 蓝牙权限获取
65 | 可以使用库`BluetoothPermissionHandler`来辅助获取蓝牙权限或者开发者自己动态获取权限,`BluetoothPermissionHandler`用法如下:
66 | ```
67 | private val permissionCallBack=BluetoothPermissionHandler(this,this)
68 | override fun onCreate(savedInstanceState: Bundle?) {
69 | permissionCallBack.start();
70 | }
71 | override fun permissionFailed() {
72 | }
73 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
74 | super.onActivityResult(requestCode, resultCode, data)
75 | permissionCallBack.onActivityResult(requestCode, resultCode, data)
76 | }
77 | override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
78 | super.onRequestPermissionsResult(requestCode, permissions, grantResults)
79 | permissionCallBack.onRequestPermissionsResult(requestCode, permissions, grantResults)
80 | }
81 | override fun onBlueToothEnabled() {
82 |
83 |
84 | }
85 | ```
86 |
87 | ### 初始化以及相关方法
88 | ---
89 | - 初始化操作可以放到任何地方
90 | `BleManager.getInstance().init(application)`
91 | - 使用前台service传输数据
92 | `BleManager.getInstance().setForegroundService(true)`
93 | - 如果使用ForegroundService模式,可自定义通知栏
94 | `BleManager.getInstance().setNotification(notification)`
95 | - 获取所有配对过的设备
96 | `BleManager.getInstance().getPairedDevices()`
97 |
98 | ## 连接
99 | 不管是服务端还是客户端都需要获取蓝牙权限,并且进行初始化BleManager。如果使用`BluetoothPermissionHandler`,应该在`onBlueToothEnabled`回调中做
100 | 扫描连接等操作。
101 |
102 | ### 设置为Server端
103 | ---
104 | #### 设置UUID
105 | 默认使用`00001101-0000-1000-8000-00805F9B34FB`,当然可以自定义
106 | ```
107 | BleManager.getInstance().setConnectionUUID()
108 | ```
109 | #### 设置设备可被扫描发现
110 | 传入参数为可被发现的时间,单位秒
111 | ```
112 | BleManager.getInstance().enableDiscoverable(300)
113 | ```
114 | #### 注册为Server
115 | 注册为Server端之后,当有设备连接成功后,会回调`connectSuccess`方法,我们可以保存回调回来的
116 | `Connect`为全局,方便读写操作
117 | ```
118 | BleManager.getInstance().registerServerConnection(object: ConnectResultlistner {
119 | override fun connectSuccess(connect: Connect?) {
120 | this@MainActivity.connect=connect
121 | read()
122 | }
123 |
124 | override fun connectFailed(e: Exception?) {
125 |
126 | }
127 |
128 | })
129 | ```
130 | ### 设置为Client端
131 | ---
132 | #### 扫描设备
133 |
134 | 配置扫描时间,然后扫描,在扫描回调中,通常操作是将回调的蓝牙设备添加到列表并显示,需要注意的是,回调的蓝牙设备可能会**重复**,因此需要手动去重
135 | ```
136 | //配置扫描时间
137 | val config=ScanConfig(5000)
138 | BleManager.getInstance().scan(config,object :ScanResultListener{
139 | override fun onDeviceFound(device: BluetoothDevice?) {
140 |
141 | }
142 |
143 | override fun onFinish() {
144 | }
145 |
146 | override fun onError() {
147 | }
148 | })
149 | ```
150 |
151 | #### 设置UUID
152 | 默认使用`00001101-0000-1000-8000-00805F9B34FB`,当然可以自定义
153 | ```
154 | BleManager.getInstance().setConnectionUUID()
155 | ```
156 |
157 | #### 配对(如果已经配对,跳过此步)
158 | 如果没有配对,需要先进行设备配对,如果已经配对,那么可以直接进行连接操作
159 | 判断是否已经配对,可以用`BleManager.getInstance().getPairedDevices()`返回的集合进行判断
160 | 配对代码如下:
161 | ```
162 | BleManager.getInstance().pin(data[p1],object:PinResultListener{
163 | override fun paired(device: BluetoothDevice?) {
164 | connect(context,data[p1])
165 | }
166 |
167 | override fun startPair(device: BluetoothDevice?) {
168 | super.startPair(device)
169 | }
170 |
171 | override fun pairing(device: BluetoothDevice?) {
172 | super.pairing(device)
173 | }
174 |
175 | override fun pairFailed(device: BluetoothDevice?) {
176 | super.pairFailed(device)
177 | }
178 | })
179 | ```
180 |
181 | #### 连接Server
182 | 当有设备连接成功后,会回调`connectSuccess`方法,我们可以保存回调回来的
183 | `Connect`为全局,方便读写操作
184 | ```
185 | BleManager.getInstance().connect(d, object : ConnectResultlistner {
186 | override fun connectSuccess(connect: Connect?) {
187 | }
188 |
189 | override fun connectFailed(e: Exception?) {
190 | }
191 | })
192 | ```
193 |
194 |
195 | ### 传输数据
196 | #### **NewFeature自定义一个完整数据包包头、包尾**
197 | ```
198 | connect?.setReadPacketVerifyListener(object : PacketDefineListener {
199 | override fun getPacketStart(): ByteArray {
200 | return start
201 |
202 | }
203 |
204 | override fun getPacketEnd(): ByteArray {
205 | return end
206 |
207 | }
208 | })
209 | ```
210 | #### 读
211 | ```
212 | connect?.read(object: TransferProgressListener {
213 | override fun transferSuccess(bytes: ByteArray?) {
214 | bytes?.let { it1 ->
215 | tvReceive.text=String(it1)
216 | }
217 | CLog.e("read string")
218 | }
219 | override fun transferFailed(msg:String) {
220 | t(msg)
221 | }
222 | override fun transfering(progress: Int) {
223 | CLog.e("read progress:$progress")
224 | }
225 | })
226 | ```
227 | #### 写
228 | ```
229 | connect?.write(text.toByteArray(), object : TransferProgressListener {
230 | override fun transferSuccess(bytes: ByteArray?) {
231 |
232 | }
233 |
234 | override fun transferFailed(msg:String) {
235 | t(msg)
236 | }
237 |
238 | override fun transfering(progress: Int) {
239 | CLog.e("write progress:$progress")
240 | }
241 | })
242 | ```
243 | ### 断开连接
244 | ```
245 | BleManager.getInstance().destory()
246 | ```
247 | ## API Function
248 | 所有功能接口
249 | ```
250 | void init(Context context);
251 | void setConnectionUUID(String uuid);
252 |
253 | boolean isSupported();
254 |
255 | void setResultListener(ScanResultListener resultListener);
256 |
257 | Set getPairedDevices();
258 |
259 | void scan(ScanConfig scanConfig, ScanResultListener scanResultListener);
260 |
261 | void stopSearch();
262 |
263 | void connect(BluetoothDevice device, ConnectResultlistner connectResultlistner);
264 | void destory();
265 | void pin(BluetoothDevice device, PinResultListener resultListener);
266 | void cancelPin(BluetoothDevice device, ResultListener resultListener);
267 | void setServerConnectResultListener(ConnectResultlistner connectResultListener);
268 | void registerServerConnection(ConnectResultlistner connectResultListener);
269 |
270 | void setForegroundService(boolean foregroundService);
271 | void setNotification(Notification notification);
272 | void enableDiscoverable(long time);
273 | ```
274 | ## demo
275 |
276 |
277 | ## TODO
278 | - [ ] 传输数据进度完善
279 | ## Last
280 | - 详细适用请看demo,第一版可能还有些不完善,持续完善中
281 | - 欢迎PR或Issues
282 | - 如果使用过程中觉得还不错,请不要吝啬你的star,哈哈。
283 | ## License
284 | ---
285 | Apache 2.0
286 |
287 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':classicbt',':app'
2 |
--------------------------------------------------------------------------------
/ui/gif.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AlexLiuSheng/EasyBluetoothFrame/43b7a1678189befceb28d49e57535fd3e8bb67bb/ui/gif.gif
--------------------------------------------------------------------------------
/ui/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AlexLiuSheng/EasyBluetoothFrame/43b7a1678189befceb28d49e57535fd3e8bb67bb/ui/logo.png
--------------------------------------------------------------------------------