├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── styles.xml
│ │ │ └── dimens.xml
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ └── values-v21
│ │ │ └── styles.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── example
│ │ └── android
│ │ └── eddystonescanner
│ │ ├── SampleBeacon.java
│ │ ├── MainActivity.java
│ │ └── EddystoneScannerService.java
├── build.gradle
└── proguard-rules.pro
├── settings.gradle
├── .gitignore
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | /local.properties
3 | /.idea/
4 | *.iml
5 | .DS_Store
6 | /build
7 | /captures
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Eddystone Scanner
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devunwired/eddystone-scanner/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devunwired/eddystone-scanner/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devunwired/eddystone-scanner/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devunwired/eddystone-scanner/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devunwired/eddystone-scanner/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Apr 10 15:27:10 PDT 2013
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-2.2.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 22
5 | buildToolsVersion "22.0.1"
6 |
7 | defaultConfig {
8 | applicationId "com.example.android.eddystonescanner"
9 | minSdkVersion 21
10 | targetSdkVersion 22
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | }
25 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/davesmith/android-sdk-mac_86/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
13 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #Eddystone Scanner#
2 | This repository contains an example of using the Android BLE APIs (21+) to scan for an Eddystone-UID beacon. You can find more information about Eddystone at https://github.com/google/eddystone
3 |
4 | ##Disclaimer##
5 |
6 | This repository contains sample code intended to demonstrate the capabilities of the Android Bluetooth LE APIs. It is not intended to be used as-is in applications as a library dependency, and will not be maintained as such. Bug fix contributions are welcome, but issues and feature requests will not be addressed.
7 |
8 | ##License##
9 |
10 | **The code supplied here is covered under the MIT Open Source License:**
11 |
12 | Copyright (c) 2015 Wireless Designs, LLC
13 |
14 | Permission is hereby granted, free of charge, to any person obtaining
15 | a copy of this software and associated documentation files (the
16 | "Software"), to deal in the Software without restriction, including
17 | without limitation the rights to use, copy, modify, merge, publish,
18 | distribute, sublicense, and/or sell copies of the Software, and to
19 | permit persons to whom the Software is furnished to do so, subject to
20 | the following conditions:
21 |
22 | The above copyright notice and this permission notice shall be
23 | included in all copies or substantial portions of the Software.
24 |
25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 |
--------------------------------------------------------------------------------
/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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
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 Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/android/eddystonescanner/SampleBeacon.java:
--------------------------------------------------------------------------------
1 | package com.example.android.eddystonescanner;
2 |
3 | import android.util.Log;
4 |
5 | import java.text.NumberFormat;
6 |
7 | /**
8 | * Simple model class to house relevant data coming from
9 | * beacon advertisements.
10 | */
11 | public class SampleBeacon {
12 | private static final String TAG = SampleBeacon.class.getSimpleName();
13 |
14 | public String deviceAddress;
15 | public String id;
16 | public int latestRssi;
17 | public long lastDetectedTimestamp;
18 |
19 | public float battery;
20 | public float temperature;
21 |
22 | public SampleBeacon(String address, int rssi, String identifier, long timestamp) {
23 | this.deviceAddress = address;
24 | this.latestRssi = rssi;
25 | this.id = identifier;
26 | this.lastDetectedTimestamp = timestamp;
27 |
28 | this.battery = -1f;
29 | this.temperature = -1f;
30 | }
31 |
32 | public void update(String address, int rssi, long timestamp) {
33 | this.deviceAddress = address;
34 | this.latestRssi = rssi;
35 | this.lastDetectedTimestamp = timestamp;
36 | }
37 |
38 | @Override
39 | public String toString() {
40 | return String.format("%s\n%ddBm Battery: %s Temperature: %s",
41 | id, latestRssi,
42 | battery < 0f ? "N/A" : String.format("%.1fV", battery),
43 | temperature < 0f ? "N/A" : String.format("%.1fC", temperature));
44 | }
45 |
46 | // Parse the instance id out of a UID packet
47 | public static String getInstanceId(byte[] data) {
48 | StringBuilder sb = new StringBuilder();
49 |
50 | //UID packets are always 18 bytes in length
51 | //Parse out the last 6 bytes for the id
52 | int packetLength = 18;
53 | int offset = packetLength - 6;
54 | for (int i=offset; i < packetLength; i++) {
55 | sb.append(Integer.toHexString(data[i] & 0xFF));
56 | }
57 |
58 | return sb.toString();
59 | }
60 |
61 | // Parse the battery level out of a TLM packet
62 | public static float getTlmBattery(byte[] data) {
63 | byte version = data[1];
64 | if (version != 0) {
65 | Log.w(TAG, "Unknown telemetry version");
66 | return -1;
67 | }
68 | int voltage = (data[2] & 0xFF) << 8;
69 | voltage += (data[3] & 0xFF);
70 |
71 | //Value is 1mV per bit
72 | return voltage / 1000f;
73 | }
74 |
75 | // Parse the temperature out of a TLM packet
76 | public static float getTlmTemperature(byte[] data) {
77 | byte version = data[1];
78 | if (version != 0) {
79 | Log.w(TAG, "Unknown telemetry version");
80 | return -1;
81 | }
82 |
83 | if (data[4] == (byte)0x80 && data[5] == (byte)0x00) {
84 | Log.w(TAG, "Temperature not supported");
85 | return -1;
86 | }
87 |
88 | int temp = (data[4] << 8);
89 | temp += (data[5] & 0xFF);
90 |
91 | return temp / 256f;
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
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 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/android/eddystonescanner/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.android.eddystonescanner;
2 |
3 | import android.app.ListActivity;
4 | import android.bluetooth.BluetoothAdapter;
5 | import android.bluetooth.BluetoothManager;
6 | import android.content.ComponentName;
7 | import android.content.Intent;
8 | import android.content.ServiceConnection;
9 | import android.content.pm.PackageManager;
10 | import android.os.Bundle;
11 | import android.os.Handler;
12 | import android.os.IBinder;
13 | import android.util.Log;
14 | import android.widget.ArrayAdapter;
15 | import android.widget.Toast;
16 |
17 | import java.util.ArrayList;
18 |
19 |
20 | public class MainActivity extends ListActivity implements
21 | ServiceConnection, EddystoneScannerService.OnBeaconEventListener {
22 | private static final String TAG = MainActivity.class.getSimpleName();
23 |
24 | private static final int EXPIRE_TIMEOUT = 5000;
25 | private static final int EXPIRE_TASK_PERIOD = 1000;
26 |
27 | private EddystoneScannerService mService;
28 | private ArrayAdapter mAdapter;
29 | private ArrayList mAdapterItems;
30 |
31 | @Override
32 | protected void onCreate(Bundle savedInstanceState) {
33 | super.onCreate(savedInstanceState);
34 | mAdapterItems = new ArrayList<>();
35 | mAdapter = new ArrayAdapter<>(this,
36 | android.R.layout.simple_list_item_1,
37 | mAdapterItems);
38 |
39 | setListAdapter(mAdapter);
40 | }
41 |
42 | @Override
43 | protected void onResume() {
44 | super.onResume();
45 | if (checkBluetoothStatus()) {
46 | Intent intent = new Intent(this, EddystoneScannerService.class);
47 | bindService(intent, this, BIND_AUTO_CREATE);
48 |
49 | mHandler.post(mPruneTask);
50 | }
51 | }
52 |
53 | @Override
54 | protected void onPause() {
55 | super.onPause();
56 | mHandler.removeCallbacks(mPruneTask);
57 |
58 | mService.setBeaconEventListener(null);
59 | unbindService(this);
60 | }
61 |
62 | /* This task checks for beacons we haven't seen in awhile */
63 | private Handler mHandler = new Handler();
64 | private Runnable mPruneTask = new Runnable() {
65 | @Override
66 | public void run() {
67 | final ArrayList expiredBeacons = new ArrayList<>();
68 | final long now = System.currentTimeMillis();
69 | for (SampleBeacon beacon : mAdapterItems) {
70 | long delta = now - beacon.lastDetectedTimestamp;
71 | if (delta >= EXPIRE_TIMEOUT) {
72 | expiredBeacons.add(beacon);
73 | }
74 | }
75 |
76 | if (!expiredBeacons.isEmpty()) {
77 | Log.d(TAG, "Found " + expiredBeacons.size() + " expired");
78 | mAdapterItems.removeAll(expiredBeacons);
79 | mAdapter.notifyDataSetChanged();
80 | }
81 |
82 | mHandler.postDelayed(this, EXPIRE_TASK_PERIOD);
83 | }
84 | };
85 |
86 | /* Verify Bluetooth Support */
87 | private boolean checkBluetoothStatus() {
88 | BluetoothManager manager =
89 | (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
90 | BluetoothAdapter adapter = manager.getAdapter();
91 | /*
92 | * We need to enforce that Bluetooth is first enabled, and take the
93 | * user to settings to enable it if they have not done so.
94 | */
95 | if (adapter == null || !adapter.isEnabled()) {
96 | //Bluetooth is disabled
97 | Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
98 | startActivity(enableBtIntent);
99 | finish();
100 | return false;
101 | }
102 |
103 | /*
104 | * Check for Bluetooth LE Support. In production, our manifest entry will keep this
105 | * from installing on these devices, but this will allow test devices or other
106 | * sideloads to report whether or not the feature exists.
107 | */
108 | if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
109 | Toast.makeText(this, "No LE Support.", Toast.LENGTH_SHORT).show();
110 | finish();
111 | return false;
112 | }
113 |
114 | return true;
115 | }
116 |
117 | /* Handle connection events to the discovery service */
118 | @Override
119 | public void onServiceConnected(ComponentName name, IBinder service) {
120 | Log.d(TAG, "Connected to scanner service");
121 | mService = ((EddystoneScannerService.LocalBinder) service).getService();
122 | mService.setBeaconEventListener(this);
123 | }
124 |
125 | @Override
126 | public void onServiceDisconnected(ComponentName name) {
127 | Log.d(TAG, "Disconnected from scanner service");
128 | mService = null;
129 | }
130 |
131 | /* Handle callback events from the discovery service */
132 | @Override
133 | public void onBeaconIdentifier(String deviceAddress, int rssi, String instanceId) {
134 | final long now = System.currentTimeMillis();
135 | for (SampleBeacon item : mAdapterItems) {
136 | if (instanceId.equals(item.id)) {
137 | //Already have this one, make sure device info is up to date
138 | item.update(deviceAddress, rssi, now);
139 | mAdapter.notifyDataSetChanged();
140 | return;
141 | }
142 | }
143 |
144 | //New beacon, add it
145 | SampleBeacon beacon =
146 | new SampleBeacon(deviceAddress, rssi, instanceId, now);
147 | mAdapterItems.add(beacon);
148 | mAdapter.notifyDataSetChanged();
149 | }
150 |
151 | @Override
152 | public void onBeaconTelemetry(String deviceAddress, float battery, float temperature) {
153 | for (SampleBeacon item : mAdapterItems) {
154 | if (deviceAddress.equals(item.deviceAddress)) {
155 | //Found it, update voltage
156 | item.battery = battery;
157 | item.temperature = temperature;
158 | mAdapter.notifyDataSetChanged();
159 | return;
160 | }
161 | }
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/android/eddystonescanner/EddystoneScannerService.java:
--------------------------------------------------------------------------------
1 | package com.example.android.eddystonescanner;
2 |
3 | import android.app.Service;
4 | import android.bluetooth.BluetoothManager;
5 | import android.bluetooth.le.BluetoothLeScanner;
6 | import android.bluetooth.le.ScanCallback;
7 | import android.bluetooth.le.ScanFilter;
8 | import android.bluetooth.le.ScanResult;
9 | import android.bluetooth.le.ScanSettings;
10 | import android.content.Intent;
11 | import android.os.Binder;
12 | import android.os.Handler;
13 | import android.os.IBinder;
14 | import android.os.Looper;
15 | import android.os.ParcelUuid;
16 | import android.util.Log;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 |
21 |
22 | public class EddystoneScannerService extends Service {
23 | private static final String TAG =
24 | EddystoneScannerService.class.getSimpleName();
25 |
26 | // …if you feel like making the log a bit noisier…
27 | private static boolean DEBUG_SCAN = false;
28 |
29 | // Eddystone service uuid (0xfeaa)
30 | private static final ParcelUuid UID_SERVICE =
31 | ParcelUuid.fromString("0000feaa-0000-1000-8000-00805f9b34fb");
32 |
33 | // Default namespace id for KST Eddystone beacons (d89bed6e130ee5cf1ba1)
34 | private static final byte[] NAMESPACE_FILTER = {
35 | 0x00, //Frame type
36 | 0x00, //TX power
37 | (byte)0xd8, (byte)0x9b, (byte)0xed, (byte)0x6e, (byte)0x13,
38 | (byte)0x0e, (byte)0xe5, (byte)0xcf, (byte)0x1b, (byte)0xa1,
39 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
40 | };
41 |
42 | // Force frame type and namespace id to match
43 | private static final byte[] NAMESPACE_FILTER_MASK = {
44 | (byte)0xFF,
45 | 0x00,
46 | (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
47 | (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF,
48 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
49 | };
50 |
51 | private static final byte[] TLM_FILTER = {
52 | 0x20, //Frame type
53 | 0x00, //Protocol version = 0
54 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
55 | 0x00, 0x00
56 | };
57 |
58 | // Force frame type and protocol to match
59 | private static final byte[] TLM_FILTER_MASK = {
60 | (byte)0xFF,
61 | (byte)0xFF,
62 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
63 | 0x00, 0x00
64 | };
65 |
66 | // Eddystone frame types
67 | private static final byte TYPE_UID = 0x00;
68 | private static final byte TYPE_URL = 0x10;
69 | private static final byte TYPE_TLM = 0x20;
70 |
71 | //Callback interface for the UI
72 | public interface OnBeaconEventListener {
73 | void onBeaconIdentifier(String deviceAddress, int rssi, String instanceId);
74 | void onBeaconTelemetry(String deviceAddress, float battery, float temperature);
75 | }
76 |
77 | private BluetoothLeScanner mBluetoothLeScanner;
78 | private OnBeaconEventListener mBeaconEventListener;
79 |
80 | @Override
81 | public void onCreate() {
82 | super.onCreate();
83 |
84 | BluetoothManager manager =
85 | (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
86 | mBluetoothLeScanner = manager.getAdapter().getBluetoothLeScanner();
87 |
88 | startScanning();
89 | }
90 |
91 | @Override
92 | public void onDestroy() {
93 | super.onDestroy();
94 |
95 | stopScanning();
96 | }
97 |
98 | public void setBeaconEventListener(OnBeaconEventListener listener) {
99 | mBeaconEventListener = listener;
100 | }
101 |
102 | /* Using as a bound service to allow event callbacks */
103 | private LocalBinder mBinder = new LocalBinder();
104 | public class LocalBinder extends Binder {
105 | public EddystoneScannerService getService() {
106 | return EddystoneScannerService.this;
107 | }
108 | }
109 |
110 | @Override
111 | public IBinder onBind(Intent intent) {
112 | return mBinder;
113 | }
114 |
115 | /* Being scanning for Eddystone advertisers */
116 | private void startScanning() {
117 | ScanFilter beaconFilter = new ScanFilter.Builder()
118 | .setServiceUuid(UID_SERVICE)
119 | .setServiceData(UID_SERVICE, NAMESPACE_FILTER, NAMESPACE_FILTER_MASK)
120 | .build();
121 |
122 | ScanFilter telemetryFilter = new ScanFilter.Builder()
123 | .setServiceUuid(UID_SERVICE)
124 | .setServiceData(UID_SERVICE, TLM_FILTER, TLM_FILTER_MASK)
125 | .build();
126 |
127 | List filters = new ArrayList<>();
128 | filters.add(beaconFilter);
129 | filters.add(telemetryFilter);
130 |
131 | ScanSettings settings = new ScanSettings.Builder()
132 | .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
133 | .build();
134 |
135 | mBluetoothLeScanner.startScan(filters, settings, mScanCallback);
136 | if (DEBUG_SCAN) Log.d(TAG, "Scanning started…");
137 | }
138 |
139 | /* Terminate scanning */
140 | private void stopScanning() {
141 | mBluetoothLeScanner.stopScan(mScanCallback);
142 | if (DEBUG_SCAN) Log.d(TAG, "Scanning stopped…");
143 | }
144 |
145 | /* Handle UID packet discovery on the main thread */
146 | private void processUidPacket(String deviceAddress, int rssi, String id) {
147 | if (DEBUG_SCAN) {
148 | Log.d(TAG, "Eddystone(" + deviceAddress + ") id = " + id);
149 | }
150 |
151 | if (mBeaconEventListener != null) {
152 | mBeaconEventListener
153 | .onBeaconIdentifier(deviceAddress, rssi, id);
154 | }
155 | }
156 |
157 | /* Handle TLM packet discovery on the main thread */
158 | private void processTlmPacket(String deviceAddress, float battery, float temp) {
159 | if (DEBUG_SCAN) {
160 | Log.d(TAG, "Eddystone(" + deviceAddress + ") battery = " + battery
161 | + ", temp = " + temp);
162 | }
163 |
164 | if (mBeaconEventListener != null) {
165 | mBeaconEventListener
166 | .onBeaconTelemetry(deviceAddress, battery, temp);
167 | }
168 | }
169 |
170 | /* Process each unique BLE scan result */
171 | private ScanCallback mScanCallback = new ScanCallback() {
172 | private Handler mCallbackHandler =
173 | new Handler(Looper.getMainLooper());
174 |
175 | @Override
176 | public void onScanResult(int callbackType, ScanResult result) {
177 | processResult(result);
178 | }
179 |
180 | @Override
181 | public void onScanFailed(int errorCode) {
182 | Log.w(TAG, "Scan Error Code: " + errorCode);
183 | }
184 |
185 | @Override
186 | public void onBatchScanResults(List results) {
187 | for (ScanResult result : results) {
188 | processResult(result);
189 | }
190 | }
191 |
192 | private void processResult(ScanResult result) {
193 | byte[] data = result.getScanRecord().getServiceData(UID_SERVICE);
194 | if (data == null) {
195 | Log.w(TAG, "Invalid Eddystone scan result.");
196 | return;
197 | }
198 |
199 | final String deviceAddress = result.getDevice().getAddress();
200 | final int rssi = result.getRssi();
201 | byte frameType = data[0];
202 | switch (frameType) {
203 | case TYPE_UID:
204 | final String id = SampleBeacon.getInstanceId(data);
205 |
206 | mCallbackHandler.post(new Runnable() {
207 | @Override
208 | public void run() {
209 | processUidPacket(deviceAddress, rssi, id);
210 | }
211 | });
212 | break;
213 | case TYPE_TLM:
214 | //Parse out battery voltage
215 | final float battery = SampleBeacon.getTlmBattery(data);
216 | final float temp = SampleBeacon.getTlmTemperature(data);
217 | mCallbackHandler.post(new Runnable() {
218 | @Override
219 | public void run() {
220 | processTlmPacket(deviceAddress, battery, temp);
221 | }
222 | });
223 | break;
224 | case TYPE_URL:
225 | //Do nothing, ignoring these
226 | return;
227 | default:
228 | Log.w(TAG, "Invalid Eddystone scan result.");
229 | }
230 | }
231 | };
232 | }
233 |
--------------------------------------------------------------------------------