Skip to content

Getting Started with Android BLE blog post #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added Android/.DS_Store
Binary file not shown.
15 changes: 15 additions & 0 deletions Android/BluetoothChat/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
3 changes: 3 additions & 0 deletions Android/BluetoothChat/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Android/BluetoothChat/.idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions Android/BluetoothChat/.idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions Android/BluetoothChat/.idea/jarRepositories.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions Android/BluetoothChat/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Android/BluetoothChat/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Android/BluetoothChat/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
52 changes: 52 additions & 0 deletions Android/BluetoothChat/app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
plugins {
id 'com.android.application'
id 'kotlin-android'
}

android {
compileSdkVersion 30
buildToolsVersion "30.0.3"

defaultConfig {
applicationId "ditto.live.bluetoothchat"
minSdkVersion 25
targetSdkVersion 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}

dependencies {

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

implementation 'androidx.fragment:fragment-ktx:1.2.5'
implementation 'com.github.bassaer:chatmessageview:2.0.1'
implementation 'de.hdodenhof:circleimageview:3.0.0'
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
}
21 changes: 21 additions & 0 deletions Android/BluetoothChat/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package ditto.live.bluetoothchat

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("ditto.live.bluetoothchat", appContext.packageName)
}
}
26 changes: 26 additions & 0 deletions Android/BluetoothChat/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ditto.live.bluetoothchat">

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.BluetoothChat">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package ditto.live.bluetoothchat

abstract class BLEMessage(val text: String)
class RemoteMessage(text: String) : BLEMessage(text)
class LocalMessage(text: String) : BLEMessage(text)
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ditto.live.bluetoothchat
import java.util.*

//App service UUID
val chatDiscoveryServiceID = UUID.fromString("42332fe8-9915-11ea-bb37-0242ac130002")

//Gatt service message characteric ID used
val chatMessageCharacteristicID = UUID.fromString("43eb0d29-4188-4c84-b1e8-73231e02af95")

//UUID to confirm device connection
val confirmCharacteristicID = UUID.fromString("f0ab5a15-b003-4653-a248-73fd504c128f")
Comment on lines +4 to +11
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While the values are the same, the names and comments of these UUIDs should match what's in the iOS app.

https://github.com/getditto/bluetooth-blog-tutorial/blob/d6354958b2e786b7b2a9d5812669355b102c5c5a/iOS/App/BluetoothChat/Constants/BluetoothConstants.swift#L12-L26

Specifically, the second UUID is used as a service ID rather than a characteristic; the third UUID is a a chat characteristic where messages are written, rather than playing any sort of "confirmation" role.

Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package ditto.live.bluetoothchat

import android.app.Application
import android.bluetooth.*
import android.bluetooth.le.*
import android.os.ParcelUuid
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData

class BluetoothScanViewModel(app: Application) : AndroidViewModel(app) {
//our variables that will be set and used for the callback of nearby discovered devices
private val _scanResults = MutableLiveData<MutableMap<String, BluetoothDevice>>()
val scanResults = _scanResults as LiveData<Map<String, BluetoothDevice>>

//get an instance of the local bluetooth adapter
private val adapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
//scanner we will use to discover nearby devices using our UUID
private var scanner: BluetoothLeScanner? = null

private var scanCallback: DeviceScanCallback? = null
private val scanFilters: List<ScanFilter>
private val scanSettings: ScanSettings

init {
scanFilters = createFilters()
scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.build()
startScan()
}

override fun onCleared() {
super.onCleared()
scanner?.stopScan(scanCallback)
scanCallback = null
}

fun startScan() {
if (scanCallback == null) {
scanner = adapter.bluetoothLeScanner
scanCallback = DeviceScanCallback()
scanner?.startScan(scanFilters, scanSettings, scanCallback)
}
}

/**
* Use our unique UUID for filtering results for Bluetooth LE scans
*/
private fun createFilters(): List<ScanFilter> {
val builder = ScanFilter.Builder()
builder.setServiceUuid(ParcelUuid(chatDiscoveryServiceID))
val filter = builder.build()
return listOf(filter)
}

/**
* A callback of device scanning
* Set our scan results for discovered devices
*/
private inner class DeviceScanCallback : ScanCallback() {
override fun onBatchScanResults(results: List<ScanResult>) {
super.onBatchScanResults(results)
val res = mutableMapOf<String, BluetoothDevice>()
for (item in results) {
item.device?.let { device ->
res[device.address] = device
}
}
_scanResults.value = res
}

override fun onScanResult(
callbackType: Int,
result: ScanResult
) {
super.onScanResult(callbackType, result)
val res = mutableMapOf<String, BluetoothDevice>()
result.device?.let { device ->
res[device.address] = device
}
_scanResults.value = res
}
}
}
Loading