├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── themes.xml
│ │ │ │ └── colors.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── vungn
│ │ │ │ └── bluetoothchat
│ │ │ │ ├── util
│ │ │ │ ├── NavRoute.kt
│ │ │ │ ├── MessageMapper.kt
│ │ │ │ ├── BluetoothHelper.kt
│ │ │ │ └── BluetoothDataTransferService.kt
│ │ │ │ ├── data
│ │ │ │ ├── BluetoothMessage.kt
│ │ │ │ ├── ConnectionResult.kt
│ │ │ │ └── BluetoothData.kt
│ │ │ │ ├── MyApplication.kt
│ │ │ │ ├── vm
│ │ │ │ ├── BluetoothViewModel.kt
│ │ │ │ └── impl
│ │ │ │ │ └── BluetoothViewModelImpl.kt
│ │ │ │ ├── di
│ │ │ │ └── BluetoothModule.kt
│ │ │ │ ├── ui
│ │ │ │ ├── theme
│ │ │ │ │ ├── Type.kt
│ │ │ │ │ ├── Color.kt
│ │ │ │ │ └── Theme.kt
│ │ │ │ ├── MainActivity.kt
│ │ │ │ ├── nav
│ │ │ │ │ └── MyNavHost.kt
│ │ │ │ └── screen
│ │ │ │ │ ├── RequirementChecklist.kt
│ │ │ │ │ ├── Chat.kt
│ │ │ │ │ └── Home.kt
│ │ │ │ ├── receiver
│ │ │ │ └── BluetoothReceiver.kt
│ │ │ │ └── repo
│ │ │ │ └── BluetoothRepo.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── vungn
│ │ │ └── bluetoothchat
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── vungn
│ │ └── bluetoothchat
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── .idea
├── .gitignore
├── compiler.xml
├── kotlinc.xml
├── misc.xml
├── gradle.xml
└── inspectionProfiles
│ └── Project_Default.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BluetoothChat
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/todo/Bluetooth_chat/main/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/util/NavRoute.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.util
2 |
3 | enum class NavRoute {
4 | REQUIRE_CHECKLIST_ROUTE,
5 | HOME_ROUTE,
6 | CHAT_ROUTE
7 | }
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/data/BluetoothMessage.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.data
2 |
3 | data class BluetoothMessage(val message: String, val sender: String, val isFromLocal: Boolean)
4 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/MyApplication.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat
2 |
3 | import android.app.Application
4 | import dagger.hilt.android.HiltAndroidApp
5 |
6 | @HiltAndroidApp
7 | class MyApplication : Application()
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Jun 15 10:18:59 ICT 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
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 | local.properties
16 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/data/ConnectionResult.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.data
2 |
3 | sealed interface ConnectionResult {
4 | object ConnectionEstablished : ConnectionResult
5 | data class TransferSuccess(val message: BluetoothMessage) : ConnectionResult
6 | data class Error(val message: String) : ConnectionResult
7 | }
8 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "BluetoothChat"
16 | include ':app'
17 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/data/BluetoothData.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.data
2 |
3 | import android.bluetooth.BluetoothDevice
4 |
5 | data class BluetoothData(
6 | val scannedDevices: Set = emptySet(),
7 | val pairedDevices: Set = emptySet(),
8 | val isConnected: Boolean = false,
9 | val isConnecting: Boolean = false,
10 | val messages: List = emptyList()
11 | )
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/vungn/bluetoothchat/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/util/MessageMapper.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.util
2 |
3 | import com.vungn.bluetoothchat.data.BluetoothMessage
4 |
5 | fun String.toBlueToothMessage(isFromLocal: Boolean): BluetoothMessage {
6 | val name = substringBeforeLast("#")
7 | val message = substringAfter("#")
8 | return BluetoothMessage(message = message, sender = name, isFromLocal = isFromLocal)
9 | }
10 |
11 | fun BluetoothMessage.toByteArray(): ByteArray = "$sender#$message".encodeToByteArray()
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/vm/BluetoothViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.vm
2 |
3 | import android.bluetooth.BluetoothDevice
4 | import com.vungn.bluetoothchat.data.BluetoothData
5 | import kotlinx.coroutines.flow.Flow
6 | import kotlinx.coroutines.flow.StateFlow
7 |
8 | interface BluetoothViewModel {
9 | val state: StateFlow
10 | val isEnable: StateFlow
11 | val errorMessage: StateFlow
12 | val data: Flow
13 | fun scanBluetooth()
14 | fun refresh()
15 | fun launchServer()
16 | fun connectToServer(device: BluetoothDevice)
17 | fun sendMessage(message: String)
18 | fun disconnect()
19 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/di/BluetoothModule.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.di
2 |
3 | import android.content.Context
4 | import com.vungn.bluetoothchat.repo.BluetoothRepo
5 | import com.vungn.bluetoothchat.util.BluetoothHelper
6 | import dagger.Module
7 | import dagger.Provides
8 | import dagger.hilt.InstallIn
9 | import dagger.hilt.android.qualifiers.ApplicationContext
10 | import dagger.hilt.components.SingletonComponent
11 | import javax.inject.Singleton
12 |
13 | @Module
14 | @InstallIn(SingletonComponent::class)
15 | object BluetoothModule {
16 |
17 | @Provides
18 | @Singleton
19 | fun bluetoothRepoProvide(@ApplicationContext context: Context): BluetoothHelper =
20 | BluetoothRepo(context)
21 | }
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/vungn/bluetoothchat/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.vungn.bluetoothchat", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/util/BluetoothHelper.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.util
2 |
3 | import android.bluetooth.BluetoothAdapter
4 | import android.bluetooth.BluetoothDevice
5 | import android.bluetooth.BluetoothManager
6 | import com.vungn.bluetoothchat.data.BluetoothMessage
7 | import com.vungn.bluetoothchat.data.ConnectionResult
8 | import kotlinx.coroutines.flow.Flow
9 | import kotlinx.coroutines.flow.StateFlow
10 |
11 | interface BluetoothHelper {
12 | val bluetoothAdapter: BluetoothAdapter
13 | val bluetoothManager: BluetoothManager
14 | val state: StateFlow
15 | val scannedDevices: StateFlow>
16 | val pairedDevices: StateFlow>
17 | fun isEnable(): Boolean
18 | fun startDiscovery()
19 | fun cancelDiscovery()
20 | fun refreshDiscovery()
21 | fun startServer(): Flow
22 | fun connectToServer(device: BluetoothDevice): Flow
23 | suspend fun tryToSendMessage(message: String): BluetoothMessage?
24 | fun closeConnections()
25 | fun release()
26 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/ui/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.ui
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.compose.foundation.layout.fillMaxSize
7 | import androidx.compose.material3.MaterialTheme
8 | import androidx.compose.material3.Surface
9 | import androidx.compose.ui.Modifier
10 | import com.vungn.bluetoothchat.ui.nav.MyNavHost
11 | import com.vungn.bluetoothchat.ui.theme.BluetoothChatTheme
12 | import dagger.hilt.android.AndroidEntryPoint
13 |
14 | @AndroidEntryPoint
15 | class MainActivity : ComponentActivity() {
16 | override fun onCreate(savedInstanceState: Bundle?) {
17 | super.onCreate(savedInstanceState)
18 | setContent {
19 | BluetoothChatTheme {
20 | // A surface container using the 'background' color from the theme
21 | Surface(
22 | modifier = Modifier.fillMaxSize(),
23 | color = MaterialTheme.colorScheme.background
24 | ) {
25 | MyNavHost()
26 | }
27 | }
28 | }
29 | }
30 |
31 | companion object {
32 | val TAG = MainActivity::class.simpleName
33 | }
34 | }
--------------------------------------------------------------------------------
/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=-Xmx2048m -Dfile.encoding=UTF-8
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 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/ui/nav/MyNavHost.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.ui.nav
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.lifecycle.viewmodel.compose.viewModel
5 | import androidx.navigation.compose.NavHost
6 | import androidx.navigation.compose.composable
7 | import androidx.navigation.compose.rememberNavController
8 | import com.vungn.bluetoothchat.ui.screen.Chat
9 | import com.vungn.bluetoothchat.ui.screen.Home
10 | import com.vungn.bluetoothchat.ui.screen.RequirementChecklist
11 | import com.vungn.bluetoothchat.util.NavRoute
12 | import com.vungn.bluetoothchat.vm.BluetoothViewModel
13 | import com.vungn.bluetoothchat.vm.impl.BluetoothViewModelImpl
14 |
15 | @Composable
16 | fun MyNavHost() {
17 | val navController = rememberNavController()
18 | val vm: BluetoothViewModel = viewModel()
19 | NavHost(
20 | navController = navController, startDestination = NavRoute.REQUIRE_CHECKLIST_ROUTE.name
21 | ) {
22 | composable(NavRoute.REQUIRE_CHECKLIST_ROUTE.name) {
23 | RequirementChecklist(viewModel = vm,
24 | navigateToHome = { navController.navigate(NavRoute.HOME_ROUTE.name) })
25 | }
26 | composable(NavRoute.HOME_ROUTE.name) {
27 | Home(viewModel = vm,
28 | navigateToChat = { navController.navigate(NavRoute.CHAT_ROUTE.name) })
29 | }
30 | composable(NavRoute.CHAT_ROUTE.name) {
31 | Chat(viewModel = vm, navigateBack = { navController.popBackStack() })
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/util/BluetoothDataTransferService.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.util
2 |
3 | import android.bluetooth.BluetoothSocket
4 | import com.vungn.bluetoothchat.data.BluetoothMessage
5 | import kotlinx.coroutines.Dispatchers
6 | import kotlinx.coroutines.flow.Flow
7 | import kotlinx.coroutines.flow.flow
8 | import kotlinx.coroutines.flow.flowOn
9 | import kotlinx.coroutines.withContext
10 | import java.io.IOException
11 |
12 | class BluetoothDataTransferService constructor(private val socket: BluetoothSocket) {
13 | fun listenForIncomingMessage(): Flow = flow {
14 | if (!socket.isConnected) {
15 | return@flow
16 | }
17 | val buffer = ByteArray(1024)
18 | while (true) {
19 | val byteCount = try {
20 | socket.inputStream.read(buffer)
21 | } catch (e: IOException) {
22 | throw TransferFailedException()
23 | }
24 | emit(
25 | buffer.decodeToString(endIndex = byteCount).toBlueToothMessage(isFromLocal = false)
26 | )
27 | }
28 | }.flowOn(Dispatchers.IO)
29 |
30 | suspend fun sendMessage(byteArray: ByteArray): Boolean {
31 | return withContext(Dispatchers.IO) {
32 | try {
33 | socket.outputStream.write(byteArray)
34 | } catch (e: IOException) {
35 | e.printStackTrace()
36 | return@withContext false
37 | }
38 | true
39 | }
40 | }
41 |
42 | class TransferFailedException : IOException()
43 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/receiver/BluetoothReceiver.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.receiver
2 |
3 | import android.annotation.SuppressLint
4 | import android.bluetooth.BluetoothAdapter
5 | import android.bluetooth.BluetoothDevice
6 | import android.content.BroadcastReceiver
7 | import android.content.Context
8 | import android.content.Intent
9 | import android.os.Build
10 | import android.util.Log
11 |
12 | @SuppressLint("MissingPermission")
13 | class BluetoothReceiver : BroadcastReceiver() {
14 | private var _bluetoothReceiverListener: BluetoothReceiverListener? = null
15 | var bluetoothReceiverListener: BluetoothReceiverListener?
16 | get() = _bluetoothReceiverListener
17 | set(value) {
18 | _bluetoothReceiverListener = value
19 | }
20 |
21 | override fun onReceive(context: Context?, intent: Intent?) {
22 | when (intent?.action) {
23 | BluetoothAdapter.ACTION_STATE_CHANGED -> {
24 | val state: Int = intent.getIntExtra(
25 | BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR
26 | )
27 | _bluetoothReceiverListener?.onStateChange(state)
28 | }
29 |
30 | BluetoothDevice.ACTION_FOUND -> {
31 | val device: BluetoothDevice? =
32 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
33 | intent.getParcelableExtra(
34 | BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java
35 | )
36 | } else {
37 | intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
38 | }
39 | if (device != null) {
40 | Log.d(TAG, "Scanned device: ${device.name}")
41 | _bluetoothReceiverListener?.onFoundDevice(device)
42 | }
43 | }
44 | }
45 | }
46 |
47 | interface BluetoothReceiverListener {
48 | fun onStateChange(state: Int)
49 | fun onFoundDevice(device: BluetoothDevice)
50 | }
51 |
52 | companion object {
53 | private val TAG = BluetoothReceiver::class.simpleName
54 | }
55 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
14 |
16 |
17 |
18 |
20 |
21 |
22 |
23 |
26 |
27 |
30 |
41 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | id 'kotlin-kapt'
5 | id 'com.google.dagger.hilt.android'
6 | }
7 |
8 | android {
9 | namespace 'com.vungn.bluetoothchat'
10 | compileSdk 33
11 |
12 | defaultConfig {
13 | applicationId "com.vungn.bluetoothchat"
14 | minSdk 24
15 | targetSdk 33
16 | versionCode 1
17 | versionName "1.0"
18 |
19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
20 | vectorDrawables {
21 | useSupportLibrary true
22 | }
23 | }
24 |
25 | buildTypes {
26 | release {
27 | minifyEnabled false
28 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
29 | }
30 | }
31 | compileOptions {
32 | sourceCompatibility JavaVersion.VERSION_1_8
33 | targetCompatibility JavaVersion.VERSION_1_8
34 | }
35 | kotlinOptions {
36 | jvmTarget = '1.8'
37 | }
38 | buildFeatures {
39 | compose true
40 | }
41 | composeOptions {
42 | kotlinCompilerExtensionVersion '1.3.2'
43 | }
44 | packagingOptions {
45 | resources {
46 | excludes += '/META-INF/{AL2.0,LGPL2.1}'
47 | }
48 | }
49 | }
50 |
51 | dependencies {
52 | // Icons
53 | implementation "androidx.compose.material:material-icons-extended:1.3.0"
54 |
55 | // Navigation component
56 | implementation "androidx.navigation:navigation-compose:2.5.3"
57 |
58 | // Hilt
59 | implementation "com.google.dagger:hilt-android:2.44"
60 | kapt "com.google.dagger:hilt-compiler:2.44"
61 |
62 | implementation 'androidx.core:core-ktx:1.8.0'
63 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
64 | implementation 'androidx.activity:activity-compose:1.5.1'
65 | implementation platform('androidx.compose:compose-bom:2022.10.00')
66 | implementation 'androidx.compose.ui:ui'
67 | implementation 'androidx.compose.ui:ui-graphics'
68 | implementation 'androidx.compose.ui:ui-tooling-preview'
69 | implementation 'androidx.compose.material3:material3'
70 | testImplementation 'junit:junit:4.13.2'
71 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
72 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
73 | androidTestImplementation platform('androidx.compose:compose-bom:2022.10.00')
74 | androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
75 | debugImplementation 'androidx.compose.ui:ui-tooling'
76 | debugImplementation 'androidx.compose.ui:ui-test-manifest'
77 | }
78 | // Allow references to generated code
79 | kapt {
80 | correctErrorTypes true
81 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.ui.theme
2 | import androidx.compose.ui.graphics.Color
3 |
4 | val md_theme_light_primary = Color(0xFF006399)
5 | val md_theme_light_onPrimary = Color(0xFFFFFFFF)
6 | val md_theme_light_primaryContainer = Color(0xFFCDE5FF)
7 | val md_theme_light_onPrimaryContainer = Color(0xFF001D32)
8 | val md_theme_light_secondary = Color(0xFF51606F)
9 | val md_theme_light_onSecondary = Color(0xFFFFFFFF)
10 | val md_theme_light_secondaryContainer = Color(0xFFD5E4F6)
11 | val md_theme_light_onSecondaryContainer = Color(0xFF0E1D2A)
12 | val md_theme_light_tertiary = Color(0xFF67587A)
13 | val md_theme_light_onTertiary = Color(0xFFFFFFFF)
14 | val md_theme_light_tertiaryContainer = Color(0xFFEEDCFF)
15 | val md_theme_light_onTertiaryContainer = Color(0xFF221533)
16 | val md_theme_light_error = Color(0xFFBA1A1A)
17 | val md_theme_light_errorContainer = Color(0xFFFFDAD6)
18 | val md_theme_light_onError = Color(0xFFFFFFFF)
19 | val md_theme_light_onErrorContainer = Color(0xFF410002)
20 | val md_theme_light_background = Color(0xFFFCFCFF)
21 | val md_theme_light_onBackground = Color(0xFF1A1C1E)
22 | val md_theme_light_surface = Color(0xFFFCFCFF)
23 | val md_theme_light_onSurface = Color(0xFF1A1C1E)
24 | val md_theme_light_surfaceVariant = Color(0xFFDEE3EB)
25 | val md_theme_light_onSurfaceVariant = Color(0xFF42474E)
26 | val md_theme_light_outline = Color(0xFF72777F)
27 | val md_theme_light_inverseOnSurface = Color(0xFFF0F0F4)
28 | val md_theme_light_inverseSurface = Color(0xFF2F3033)
29 | val md_theme_light_inversePrimary = Color(0xFF95CCFF)
30 | val md_theme_light_shadow = Color(0xFF000000)
31 | val md_theme_light_surfaceTint = Color(0xFF006399)
32 | val md_theme_light_outlineVariant = Color(0xFFC2C7CF)
33 | val md_theme_light_scrim = Color(0xFF000000)
34 |
35 | val md_theme_dark_primary = Color(0xFF95CCFF)
36 | val md_theme_dark_onPrimary = Color(0xFF003352)
37 | val md_theme_dark_primaryContainer = Color(0xFF004A75)
38 | val md_theme_dark_onPrimaryContainer = Color(0xFFCDE5FF)
39 | val md_theme_dark_secondary = Color(0xFFB9C8DA)
40 | val md_theme_dark_onSecondary = Color(0xFF233240)
41 | val md_theme_dark_secondaryContainer = Color(0xFF3A4857)
42 | val md_theme_dark_onSecondaryContainer = Color(0xFFD5E4F6)
43 | val md_theme_dark_tertiary = Color(0xFFD2BFE7)
44 | val md_theme_dark_onTertiary = Color(0xFF382A49)
45 | val md_theme_dark_tertiaryContainer = Color(0xFF4F4061)
46 | val md_theme_dark_onTertiaryContainer = Color(0xFFEEDCFF)
47 | val md_theme_dark_error = Color(0xFFFFB4AB)
48 | val md_theme_dark_errorContainer = Color(0xFF93000A)
49 | val md_theme_dark_onError = Color(0xFF690005)
50 | val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
51 | val md_theme_dark_background = Color(0xFF1A1C1E)
52 | val md_theme_dark_onBackground = Color(0xFFE2E2E5)
53 | val md_theme_dark_surface = Color(0xFF1A1C1E)
54 | val md_theme_dark_onSurface = Color(0xFFE2E2E5)
55 | val md_theme_dark_surfaceVariant = Color(0xFF42474E)
56 | val md_theme_dark_onSurfaceVariant = Color(0xFFC2C7CF)
57 | val md_theme_dark_outline = Color(0xFF8C9198)
58 | val md_theme_dark_inverseOnSurface = Color(0xFF1A1C1E)
59 | val md_theme_dark_inverseSurface = Color(0xFFE2E2E5)
60 | val md_theme_dark_inversePrimary = Color(0xFF006399)
61 | val md_theme_dark_shadow = Color(0xFF000000)
62 | val md_theme_dark_surfaceTint = Color(0xFF95CCFF)
63 | val md_theme_dark_outlineVariant = Color(0xFF42474E)
64 | val md_theme_dark_scrim = Color(0xFF000000)
65 |
66 |
67 | val seed = Color(0xFF006399)
68 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.SideEffect
13 | import androidx.compose.ui.graphics.toArgb
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalView
16 | import androidx.core.view.WindowCompat
17 |
18 | private val DarkColorScheme = darkColorScheme(
19 | primary = md_theme_dark_primary,
20 | onPrimary = md_theme_dark_onPrimary,
21 | primaryContainer = md_theme_dark_primaryContainer,
22 | onPrimaryContainer = md_theme_dark_onPrimaryContainer,
23 | secondary = md_theme_dark_secondary,
24 | onSecondary = md_theme_dark_onSecondary,
25 | secondaryContainer = md_theme_dark_secondaryContainer,
26 | onSecondaryContainer = md_theme_dark_onSecondaryContainer,
27 | tertiary = md_theme_dark_tertiary,
28 | onTertiary = md_theme_dark_onTertiary,
29 | tertiaryContainer = md_theme_dark_tertiaryContainer,
30 | onTertiaryContainer = md_theme_dark_onTertiaryContainer,
31 | error = md_theme_dark_error,
32 | errorContainer = md_theme_dark_errorContainer,
33 | onError = md_theme_dark_onError,
34 | onErrorContainer = md_theme_dark_onErrorContainer,
35 | background = md_theme_dark_background,
36 | onBackground = md_theme_dark_onBackground,
37 | surface = md_theme_dark_surface,
38 | onSurface = md_theme_dark_onSurface,
39 | surfaceVariant = md_theme_dark_surfaceVariant,
40 | onSurfaceVariant = md_theme_dark_onSurfaceVariant,
41 | outline = md_theme_dark_outline,
42 | inverseOnSurface = md_theme_dark_inverseOnSurface,
43 | inverseSurface = md_theme_dark_inverseSurface,
44 | inversePrimary = md_theme_dark_inversePrimary,
45 | surfaceTint = md_theme_dark_surfaceTint,
46 | outlineVariant = md_theme_dark_outlineVariant,
47 | scrim = md_theme_dark_scrim,
48 | )
49 |
50 | private val LightColorScheme = lightColorScheme(
51 | primary = md_theme_light_primary,
52 | onPrimary = md_theme_light_onPrimary,
53 | primaryContainer = md_theme_light_primaryContainer,
54 | onPrimaryContainer = md_theme_light_onPrimaryContainer,
55 | secondary = md_theme_light_secondary,
56 | onSecondary = md_theme_light_onSecondary,
57 | secondaryContainer = md_theme_light_secondaryContainer,
58 | onSecondaryContainer = md_theme_light_onSecondaryContainer,
59 | tertiary = md_theme_light_tertiary,
60 | onTertiary = md_theme_light_onTertiary,
61 | tertiaryContainer = md_theme_light_tertiaryContainer,
62 | onTertiaryContainer = md_theme_light_onTertiaryContainer,
63 | error = md_theme_light_error,
64 | errorContainer = md_theme_light_errorContainer,
65 | onError = md_theme_light_onError,
66 | onErrorContainer = md_theme_light_onErrorContainer,
67 | background = md_theme_light_background,
68 | onBackground = md_theme_light_onBackground,
69 | surface = md_theme_light_surface,
70 | onSurface = md_theme_light_onSurface,
71 | surfaceVariant = md_theme_light_surfaceVariant,
72 | onSurfaceVariant = md_theme_light_onSurfaceVariant,
73 | outline = md_theme_light_outline,
74 | inverseOnSurface = md_theme_light_inverseOnSurface,
75 | inverseSurface = md_theme_light_inverseSurface,
76 | inversePrimary = md_theme_light_inversePrimary,
77 | surfaceTint = md_theme_light_surfaceTint,
78 | outlineVariant = md_theme_light_outlineVariant,
79 | scrim = md_theme_light_scrim,
80 | )
81 |
82 | @Composable
83 | fun BluetoothChatTheme(
84 | darkTheme: Boolean = isSystemInDarkTheme(),
85 | // Dynamic color is available on Android 12+
86 | dynamicColor: Boolean = true,
87 | content: @Composable () -> Unit
88 | ) {
89 | val colorScheme = when {
90 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
91 | val context = LocalContext.current
92 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
93 | }
94 |
95 | darkTheme -> DarkColorScheme
96 | else -> LightColorScheme
97 | }
98 | val view = LocalView.current
99 | if (!view.isInEditMode) {
100 | SideEffect {
101 | val window = (view.context as Activity).window
102 | window.statusBarColor = colorScheme.primary.toArgb()
103 | WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
104 | }
105 | }
106 |
107 | MaterialTheme(
108 | colorScheme = colorScheme,
109 | typography = Typography,
110 | content = content
111 | )
112 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/vm/impl/BluetoothViewModelImpl.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.vm.impl
2 |
3 | import android.bluetooth.BluetoothDevice
4 | import android.util.Log
5 | import androidx.lifecycle.ViewModel
6 | import androidx.lifecycle.viewModelScope
7 | import com.vungn.bluetoothchat.data.BluetoothData
8 | import com.vungn.bluetoothchat.data.ConnectionResult
9 | import com.vungn.bluetoothchat.util.BluetoothHelper
10 | import com.vungn.bluetoothchat.vm.BluetoothViewModel
11 | import dagger.hilt.android.lifecycle.HiltViewModel
12 | import kotlinx.coroutines.Dispatchers
13 | import kotlinx.coroutines.Job
14 | import kotlinx.coroutines.flow.Flow
15 | import kotlinx.coroutines.flow.MutableStateFlow
16 | import kotlinx.coroutines.flow.SharingStarted
17 | import kotlinx.coroutines.flow.StateFlow
18 | import kotlinx.coroutines.flow.catch
19 | import kotlinx.coroutines.flow.combine
20 | import kotlinx.coroutines.flow.launchIn
21 | import kotlinx.coroutines.flow.onEach
22 | import kotlinx.coroutines.flow.stateIn
23 | import kotlinx.coroutines.flow.update
24 | import kotlinx.coroutines.launch
25 | import javax.inject.Inject
26 |
27 | @HiltViewModel
28 | class BluetoothViewModelImpl @Inject constructor(private val bluetoothHelper: BluetoothHelper) :
29 | ViewModel(), BluetoothViewModel {
30 | private val _state = bluetoothHelper.state
31 | private val _isEnable = MutableStateFlow(bluetoothHelper.isEnable())
32 | private val _data = MutableStateFlow(BluetoothData())
33 | private val _errorMessage = MutableStateFlow(null)
34 | private var deviceConnectionJob: Job? = null
35 |
36 | override val state: StateFlow
37 | get() = _state
38 |
39 | override val isEnable: StateFlow
40 | get() = _isEnable
41 |
42 | override val data = combine(
43 | bluetoothHelper.scannedDevices, bluetoothHelper.pairedDevices, _data
44 | ) { scannedDevices, pairedDevices, data ->
45 | data.copy(
46 | scannedDevices = scannedDevices, pairedDevices = pairedDevices
47 | )
48 | }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), _data.value)
49 |
50 | override val errorMessage: StateFlow
51 | get() = _errorMessage
52 |
53 | override fun scanBluetooth() {
54 | bluetoothHelper.startDiscovery()
55 | }
56 |
57 | override fun refresh() {
58 | bluetoothHelper.refreshDiscovery()
59 | }
60 |
61 | override fun launchServer() {
62 | _data.update { bluetoothData -> bluetoothData.copy(isConnecting = true) }
63 | deviceConnectionJob = bluetoothHelper.startServer().listen()
64 | }
65 |
66 | override fun connectToServer(device: BluetoothDevice) {
67 | deviceConnectionJob = bluetoothHelper.connectToServer(device).listen()
68 | }
69 |
70 | override fun disconnect() {
71 | deviceConnectionJob?.cancel()
72 | bluetoothHelper.closeConnections()
73 | _data.update { bluetoothData ->
74 | bluetoothData.copy(isConnecting = false, isConnected = false)
75 | }
76 | }
77 |
78 | override fun sendMessage(message: String) {
79 | viewModelScope.launch(Dispatchers.IO) {
80 | val bluetoothMessage = bluetoothHelper.tryToSendMessage(message)
81 | if (bluetoothMessage != null) {
82 | _data.update { bluetoothData ->
83 | bluetoothData.copy(messages = bluetoothData.messages + bluetoothMessage)
84 | }
85 | } else {
86 | _errorMessage.emit("Message sending failed")
87 | }
88 | }
89 | }
90 |
91 | override fun onCleared() {
92 | super.onCleared()
93 | bluetoothHelper.release()
94 | Log.d(TAG, "onCleared: BluetoothHelper is released")
95 | }
96 |
97 | private fun Flow.listen(): Job = onEach { result ->
98 | when (result) {
99 | is ConnectionResult.ConnectionEstablished -> {
100 | Log.d(TAG, "Server connect success")
101 | _data.update { bluetoothData ->
102 | bluetoothData.copy(isConnected = true, isConnecting = false)
103 | }
104 | }
105 |
106 | is ConnectionResult.TransferSuccess -> {
107 | Log.d(TAG, "Message transferring success")
108 | _data.update { bluetoothData ->
109 | bluetoothData.copy(messages = bluetoothData.messages + result.message)
110 | }
111 | }
112 |
113 | is ConnectionResult.Error -> {
114 | Log.e(TAG, "Server connect failure")
115 | _data.update { bluetoothData ->
116 | bluetoothData.copy(isConnected = false, isConnecting = false)
117 | }
118 | _errorMessage.emit(result.message)
119 | }
120 | }
121 | }.catch { e ->
122 | Log.e(TAG, "Job flow ConnectionResult failure", e)
123 | _errorMessage.emit(e.message)
124 | bluetoothHelper.closeConnections()
125 | _data.update { bluetoothData ->
126 | bluetoothData.copy(isConnected = false, isConnecting = false)
127 | }
128 | }.launchIn(viewModelScope)
129 |
130 | companion object {
131 | private val TAG = BluetoothViewModelImpl::class.simpleName
132 | }
133 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/ui/screen/RequirementChecklist.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.ui.screen
2 |
3 | import android.Manifest
4 | import android.bluetooth.BluetoothAdapter
5 | import android.content.Intent
6 | import android.os.Build
7 | import android.util.Log
8 | import androidx.activity.compose.rememberLauncherForActivityResult
9 | import androidx.activity.result.contract.ActivityResultContracts
10 | import androidx.compose.foundation.layout.Arrangement
11 | import androidx.compose.foundation.layout.Column
12 | import androidx.compose.foundation.layout.Row
13 | import androidx.compose.foundation.layout.fillMaxSize
14 | import androidx.compose.foundation.layout.fillMaxWidth
15 | import androidx.compose.foundation.layout.padding
16 | import androidx.compose.material.icons.Icons
17 | import androidx.compose.material.icons.rounded.Check
18 | import androidx.compose.material3.Button
19 | import androidx.compose.material3.Icon
20 | import androidx.compose.material3.MaterialTheme
21 | import androidx.compose.material3.Text
22 | import androidx.compose.runtime.Composable
23 | import androidx.compose.runtime.LaunchedEffect
24 | import androidx.compose.runtime.collectAsState
25 | import androidx.compose.runtime.getValue
26 | import androidx.compose.runtime.mutableStateOf
27 | import androidx.compose.runtime.remember
28 | import androidx.compose.runtime.setValue
29 | import androidx.compose.ui.Alignment
30 | import androidx.compose.ui.Modifier
31 | import androidx.compose.ui.text.font.FontWeight
32 | import androidx.compose.ui.unit.dp
33 | import com.vungn.bluetoothchat.ui.MainActivity.Companion.TAG
34 | import com.vungn.bluetoothchat.vm.BluetoothViewModel
35 |
36 | @Composable
37 | fun RequirementChecklist(
38 | modifier: Modifier = Modifier,
39 | viewModel: BluetoothViewModel,
40 | navigateToHome: () -> Unit = {}
41 | ) {
42 | val state by viewModel.state.collectAsState()
43 | var areGranted by remember { mutableStateOf(false) }
44 | val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
45 | arrayOf(
46 | Manifest.permission.BLUETOOTH,
47 | Manifest.permission.BLUETOOTH_ADMIN,
48 | Manifest.permission.BLUETOOTH_SCAN,
49 | Manifest.permission.BLUETOOTH_PRIVILEGED,
50 | Manifest.permission.BLUETOOTH_ADVERTISE,
51 | Manifest.permission.BLUETOOTH_CONNECT,
52 | Manifest.permission.ACCESS_FINE_LOCATION
53 | )
54 | } else {
55 | arrayOf(
56 | Manifest.permission.BLUETOOTH,
57 | Manifest.permission.BLUETOOTH_ADMIN,
58 | Manifest.permission.ACCESS_FINE_LOCATION
59 | )
60 | }
61 | val permissionsRequest = rememberLauncherForActivityResult(
62 | contract = ActivityResultContracts.RequestMultiplePermissions(),
63 | onResult = { result ->
64 | areGranted = result.values.all { true }
65 | Log.d(TAG, "Are all permissions granted: $areGranted")
66 | })
67 | val bluetoothRequest = rememberLauncherForActivityResult(
68 | contract = ActivityResultContracts.StartActivityForResult(),
69 | onResult = {})
70 |
71 | LaunchedEffect(key1 = true, block = {
72 | permissionsRequest.launch(permissions)
73 | val bluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
74 | bluetoothRequest.launch(bluetoothIntent)
75 | })
76 |
77 | LaunchedEffect(key1 = state, key2 = areGranted,
78 | block = {
79 | if (state == BluetoothAdapter.STATE_ON && areGranted) {
80 | navigateToHome()
81 | }
82 | })
83 |
84 | Column(
85 | modifier = modifier
86 | .fillMaxSize()
87 | .padding(20.dp), verticalArrangement = Arrangement.Center
88 | ) {
89 | Text(
90 | text = "You need to",
91 | style = MaterialTheme.typography.titleLarge,
92 | fontWeight = FontWeight(500)
93 | )
94 | Row(
95 | modifier = Modifier.fillMaxWidth(),
96 | horizontalArrangement = Arrangement.SpaceBetween,
97 | verticalAlignment = Alignment.CenterVertically
98 | ) {
99 | Text(text = "Accept all permissions", style = MaterialTheme.typography.bodyMedium)
100 | if (areGranted) {
101 | Icon(
102 | imageVector = Icons.Rounded.Check,
103 | contentDescription = null,
104 | tint = MaterialTheme.colorScheme.primary
105 | )
106 | } else {
107 | Button(onClick = { permissionsRequest.launch(permissions) }) {
108 | Text(text = "Request")
109 | }
110 | }
111 | }
112 | Row(
113 | modifier = Modifier.fillMaxWidth(),
114 | horizontalArrangement = Arrangement.SpaceBetween,
115 | verticalAlignment = Alignment.CenterVertically
116 | ) {
117 | Text(text = "Turn on bluetooth", style = MaterialTheme.typography.bodyMedium)
118 | when (state) {
119 | BluetoothAdapter.STATE_ON -> {
120 | Icon(
121 | imageVector = Icons.Rounded.Check,
122 | contentDescription = null,
123 | tint = MaterialTheme.colorScheme.primary
124 | )
125 | }
126 |
127 | BluetoothAdapter.STATE_OFF -> {
128 | Button(onClick = {
129 | val bluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
130 | bluetoothRequest.launch(bluetoothIntent)
131 | }) {
132 | Text(text = "Turn on")
133 | }
134 | }
135 | }
136 | }
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/repo/BluetoothRepo.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.repo
2 |
3 | import android.annotation.SuppressLint
4 | import android.bluetooth.BluetoothAdapter
5 | import android.bluetooth.BluetoothDevice
6 | import android.bluetooth.BluetoothManager
7 | import android.bluetooth.BluetoothServerSocket
8 | import android.bluetooth.BluetoothSocket
9 | import android.content.Context
10 | import android.content.IntentFilter
11 | import android.util.Log
12 | import com.vungn.bluetoothchat.data.BluetoothMessage
13 | import com.vungn.bluetoothchat.data.ConnectionResult
14 | import com.vungn.bluetoothchat.receiver.BluetoothReceiver
15 | import com.vungn.bluetoothchat.util.BluetoothDataTransferService
16 | import com.vungn.bluetoothchat.util.BluetoothHelper
17 | import com.vungn.bluetoothchat.util.toByteArray
18 | import kotlinx.coroutines.Dispatchers
19 | import kotlinx.coroutines.flow.Flow
20 | import kotlinx.coroutines.flow.MutableStateFlow
21 | import kotlinx.coroutines.flow.StateFlow
22 | import kotlinx.coroutines.flow.emitAll
23 | import kotlinx.coroutines.flow.flow
24 | import kotlinx.coroutines.flow.flowOn
25 | import kotlinx.coroutines.flow.map
26 | import kotlinx.coroutines.flow.onCompletion
27 | import kotlinx.coroutines.flow.update
28 | import java.io.IOException
29 | import java.util.UUID
30 |
31 | @SuppressLint("MissingPermission")
32 | class BluetoothRepo constructor(private val context: Context) : BluetoothHelper {
33 | private val bluetoothReceiverListener = object : BluetoothReceiver.BluetoothReceiverListener {
34 | override fun onStateChange(state: Int) {
35 | _state.value = state
36 | }
37 |
38 | override fun onFoundDevice(device: BluetoothDevice) {
39 | _scannedDevices.update { devices ->
40 | devices + device
41 | }
42 | }
43 | }
44 |
45 | private val bluetoothReceiver = BluetoothReceiver().also {
46 | it.bluetoothReceiverListener = bluetoothReceiverListener
47 | }
48 | private val _bluetoothManager by lazy {
49 | context.getSystemService(BluetoothManager::class.java)
50 | }
51 | private val _bluetoothAdapter by lazy {
52 | _bluetoothManager.adapter
53 | }
54 | private val _state =
55 | MutableStateFlow(if (isEnable()) BluetoothAdapter.STATE_ON else BluetoothAdapter.STATE_OFF)
56 | private val _scannedDevices = MutableStateFlow(setOf())
57 | private val _pairedDevices = MutableStateFlow(setOf())
58 | private var _currentServerSocket: BluetoothServerSocket? = null
59 | private var _currentClientSocket: BluetoothSocket? = null
60 | private var _dataTransferService: BluetoothDataTransferService? = null
61 |
62 | init {
63 | val intent = IntentFilter().also {
64 | it.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
65 | it.addAction(BluetoothDevice.ACTION_FOUND)
66 | }
67 | context.registerReceiver(bluetoothReceiver, intent)
68 | }
69 |
70 | override val bluetoothManager: BluetoothManager
71 | get() = _bluetoothManager
72 |
73 | override val bluetoothAdapter: BluetoothAdapter
74 | get() = _bluetoothAdapter
75 |
76 | override val state: StateFlow
77 | get() = _state
78 |
79 | override val scannedDevices: StateFlow>
80 | get() = _scannedDevices
81 |
82 | override val pairedDevices: StateFlow>
83 | get() = _pairedDevices
84 |
85 | override fun isEnable(): Boolean = _bluetoothAdapter.isEnabled
86 |
87 | override fun startDiscovery() {
88 | _scannedDevices.update { setOf() }
89 | updatePairDevices()
90 | _bluetoothAdapter.startDiscovery()
91 | }
92 |
93 | override fun cancelDiscovery() {
94 | _bluetoothAdapter.cancelDiscovery()
95 | }
96 |
97 | override fun refreshDiscovery() {
98 | cancelDiscovery()
99 | startDiscovery()
100 | }
101 |
102 | override fun release() {
103 | context.unregisterReceiver(bluetoothReceiver)
104 | }
105 |
106 | override fun startServer(): Flow = flow {
107 | _bluetoothAdapter.cancelDiscovery()
108 | _currentServerSocket = _bluetoothAdapter.listenUsingRfcommWithServiceRecord(
109 | NAME, UUID_STRING
110 | )
111 |
112 | var shouldLoop = true
113 | while (shouldLoop) {
114 | _currentClientSocket = try {
115 | _currentServerSocket?.accept()
116 | } catch (e: IOException) {
117 | Log.e(TAG, "Socket's accept() method failed", e)
118 | emit(ConnectionResult.Error(e.message.toString()))
119 | shouldLoop = false
120 | null
121 | }
122 | emit(ConnectionResult.ConnectionEstablished)
123 | _currentClientSocket?.also { socket ->
124 | BluetoothDataTransferService(socket).also { service ->
125 | _dataTransferService = service
126 | emitAll(service.listenForIncomingMessage().map { bluetoothMessage ->
127 | ConnectionResult.TransferSuccess(bluetoothMessage)
128 | })
129 | }
130 | _currentServerSocket?.close()
131 | shouldLoop = false
132 | }
133 | }
134 | }.onCompletion { closeConnections() }.flowOn(Dispatchers.IO)
135 |
136 | override fun connectToServer(device: BluetoothDevice): Flow = flow {
137 | _bluetoothAdapter.cancelDiscovery()
138 | _currentClientSocket = _bluetoothAdapter?.getRemoteDevice(device.address)
139 | ?.createRfcommSocketToServiceRecord(UUID_STRING)
140 |
141 | _currentClientSocket?.let { socket ->
142 | try {
143 | socket.connect()
144 | emit(ConnectionResult.ConnectionEstablished)
145 | BluetoothDataTransferService(socket).also { service ->
146 | _dataTransferService = service
147 | emitAll(service.listenForIncomingMessage().map { bluetoothMessage ->
148 | ConnectionResult.TransferSuccess(bluetoothMessage)
149 | })
150 | }
151 | } catch (e: IOException) {
152 | Log.e(TAG, "connectToServer", e)
153 | socket.close()
154 | _currentClientSocket = null
155 | emit(ConnectionResult.Error(e.message.toString()))
156 | }
157 | }
158 | }.onCompletion { closeConnections() }.flowOn(Dispatchers.IO)
159 |
160 | override suspend fun tryToSendMessage(message: String): BluetoothMessage? {
161 | if (_dataTransferService == null) {
162 | return null
163 | }
164 | val bluetoothMessage = BluetoothMessage(
165 | message = message, sender = _bluetoothAdapter.name ?: "Unknown name", isFromLocal = true
166 | )
167 | _dataTransferService?.sendMessage(bluetoothMessage.toByteArray()).let { isSend ->
168 | if (isSend == true) {
169 | return bluetoothMessage
170 | }
171 | }
172 | return null
173 | }
174 |
175 | private fun updatePairDevices() {
176 | _pairedDevices.update { _bluetoothAdapter.bondedDevices }
177 | }
178 |
179 | override fun closeConnections() {
180 | _currentServerSocket?.close()
181 | _currentClientSocket?.close()
182 | _currentServerSocket = null
183 | _currentClientSocket = null
184 | }
185 |
186 | companion object {
187 | private val TAG = BluetoothRepo::class.simpleName
188 | private const val NAME = "com.vungn.bluetoothchat.Name"
189 | private val UUID_STRING = UUID.fromString("27b7d1da-08c7-4505-a6d1-2459987e5e2d")
190 | }
191 | }
192 |
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/ui/screen/Chat.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.ui.screen
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.interaction.MutableInteractionSource
6 | import androidx.compose.foundation.layout.Arrangement
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.PaddingValues
9 | import androidx.compose.foundation.layout.Row
10 | import androidx.compose.foundation.layout.fillMaxSize
11 | import androidx.compose.foundation.layout.fillMaxWidth
12 | import androidx.compose.foundation.layout.padding
13 | import androidx.compose.foundation.lazy.LazyColumn
14 | import androidx.compose.foundation.lazy.items
15 | import androidx.compose.foundation.lazy.rememberLazyListState
16 | import androidx.compose.foundation.shape.RoundedCornerShape
17 | import androidx.compose.material.icons.Icons
18 | import androidx.compose.material.icons.rounded.ArrowBack
19 | import androidx.compose.material.icons.rounded.Image
20 | import androidx.compose.material.icons.rounded.Send
21 | import androidx.compose.material3.ExperimentalMaterial3Api
22 | import androidx.compose.material3.Icon
23 | import androidx.compose.material3.IconButton
24 | import androidx.compose.material3.MaterialTheme
25 | import androidx.compose.material3.Scaffold
26 | import androidx.compose.material3.Snackbar
27 | import androidx.compose.material3.SnackbarHost
28 | import androidx.compose.material3.SnackbarHostState
29 | import androidx.compose.material3.Text
30 | import androidx.compose.material3.TextButton
31 | import androidx.compose.material3.TextField
32 | import androidx.compose.material3.TopAppBar
33 | import androidx.compose.runtime.Composable
34 | import androidx.compose.runtime.LaunchedEffect
35 | import androidx.compose.runtime.collectAsState
36 | import androidx.compose.runtime.getValue
37 | import androidx.compose.runtime.mutableStateOf
38 | import androidx.compose.runtime.remember
39 | import androidx.compose.runtime.setValue
40 | import androidx.compose.ui.Alignment
41 | import androidx.compose.ui.ExperimentalComposeUiApi
42 | import androidx.compose.ui.Modifier
43 | import androidx.compose.ui.draw.clip
44 | import androidx.compose.ui.platform.LocalFocusManager
45 | import androidx.compose.ui.platform.LocalSoftwareKeyboardController
46 | import androidx.compose.ui.unit.dp
47 | import com.vungn.bluetoothchat.data.BluetoothData
48 | import com.vungn.bluetoothchat.vm.BluetoothViewModel
49 |
50 | @OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
51 | @Composable
52 | fun Chat(
53 | modifier: Modifier = Modifier, viewModel: BluetoothViewModel, navigateBack: () -> Boolean
54 | ) {
55 | val data by viewModel.data.collectAsState(initial = BluetoothData())
56 | val errorMessage by viewModel.errorMessage.collectAsState()
57 | val lazyListState = rememberLazyListState()
58 | val snackBarHostState = remember { SnackbarHostState() }
59 | val kc = LocalSoftwareKeyboardController.current
60 | val focusManager = LocalFocusManager.current
61 | val interactionSource = remember { MutableInteractionSource() }
62 | var message by remember { mutableStateOf("") }
63 |
64 | LaunchedEffect(key1 = data.messages, block = {
65 | if (data.messages.isNotEmpty()) {
66 | lazyListState.scrollToItem(data.messages.size - 1)
67 | }
68 | })
69 | LaunchedEffect(key1 = errorMessage, block = {
70 | if (errorMessage != null) {
71 | snackBarHostState.showSnackbar(errorMessage.toString())
72 | }
73 | })
74 |
75 | Scaffold(modifier = modifier
76 | .fillMaxSize()
77 | .clickable(indication = null, interactionSource = interactionSource) { kc?.hide() },
78 | topBar = {
79 | TopAppBar(title = { Text(text = "Chat") }, navigationIcon = {
80 | IconButton(onClick = {
81 | viewModel.disconnect()
82 | navigateBack()
83 | }) {
84 | Icon(imageVector = Icons.Rounded.ArrowBack, contentDescription = "Go back")
85 | }
86 | })
87 | },
88 | bottomBar = {
89 | TextField(modifier = Modifier.fillMaxWidth(),
90 | value = message,
91 | onValueChange = { message = it },
92 | placeholder = { Text(text = "Message") },
93 | leadingIcon = {
94 | Row {
95 | IconButton(onClick = { /*TODO*/ }) {
96 | Icon(
97 | imageVector = Icons.Rounded.Image,
98 | contentDescription = "Choose images"
99 | )
100 | }
101 | }
102 | },
103 | trailingIcon = {
104 | IconButton(onClick = {
105 | viewModel.sendMessage(message = message)
106 | message = ""
107 | kc?.hide()
108 | focusManager.clearFocus()
109 | }) {
110 | Icon(imageVector = Icons.Rounded.Send, contentDescription = "Send message")
111 | }
112 | })
113 | },
114 | snackbarHost = {
115 | SnackbarHost(hostState = snackBarHostState) { data ->
116 | Snackbar(modifier = Modifier.padding(12.dp), action = {
117 | TextButton(onClick = {
118 | viewModel.disconnect()
119 | navigateBack()
120 | }) {
121 | Text(text = "Disconnect")
122 | }
123 | }) {
124 | Text(text = data.visuals.message)
125 | }
126 | }
127 | }) { paddingValues ->
128 | Column(
129 | modifier = Modifier
130 | .fillMaxSize()
131 | .padding(paddingValues),
132 | verticalArrangement = Arrangement.Bottom
133 | ) {
134 | LazyColumn(
135 | modifier = Modifier.fillMaxWidth(),
136 | contentPadding = PaddingValues(10.dp),
137 | verticalArrangement = Arrangement.spacedBy(10.dp),
138 | state = lazyListState
139 | ) {
140 | items(data.messages) { message ->
141 | Column(
142 | modifier = Modifier.fillMaxWidth()
143 | ) {
144 | Column(
145 | modifier = Modifier
146 | .clip(
147 | shape = if (message.isFromLocal) RoundedCornerShape(
148 | topStart = 20.dp,
149 | topEnd = 20.dp,
150 | bottomStart = 20.dp,
151 | bottomEnd = 0.dp
152 | )
153 | else RoundedCornerShape(
154 | topStart = 20.dp,
155 | topEnd = 20.dp,
156 | bottomStart = 0.dp,
157 | bottomEnd = 20.dp
158 | )
159 | )
160 | .background(
161 | if (message.isFromLocal) MaterialTheme.colorScheme.primary
162 | else MaterialTheme.colorScheme.primary.copy(alpha = 0.1f)
163 | )
164 | .padding(10.dp)
165 | .align(if (message.isFromLocal) Alignment.End else Alignment.Start),
166 | horizontalAlignment = if (message.isFromLocal) Alignment.End else Alignment.Start
167 | ) {
168 | Text(
169 | style = MaterialTheme.typography.titleMedium,
170 | text = message.sender,
171 | color = if (message.isFromLocal) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onBackground
172 | )
173 | Text(
174 | style = MaterialTheme.typography.bodyMedium,
175 | text = message.message,
176 | color = if (message.isFromLocal) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onBackground
177 | )
178 | }
179 | }
180 | }
181 | }
182 | }
183 | }
184 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/vungn/bluetoothchat/ui/screen/Home.kt:
--------------------------------------------------------------------------------
1 | package com.vungn.bluetoothchat.ui.screen
2 |
3 | import android.annotation.SuppressLint
4 | import androidx.compose.foundation.background
5 | import androidx.compose.foundation.clickable
6 | import androidx.compose.foundation.isSystemInDarkTheme
7 | import androidx.compose.foundation.layout.Arrangement
8 | import androidx.compose.foundation.layout.Box
9 | import androidx.compose.foundation.layout.Column
10 | import androidx.compose.foundation.layout.Row
11 | import androidx.compose.foundation.layout.Spacer
12 | import androidx.compose.foundation.layout.fillMaxSize
13 | import androidx.compose.foundation.layout.fillMaxWidth
14 | import androidx.compose.foundation.layout.padding
15 | import androidx.compose.foundation.lazy.LazyColumn
16 | import androidx.compose.foundation.lazy.itemsIndexed
17 | import androidx.compose.foundation.shape.CornerSize
18 | import androidx.compose.foundation.shape.RoundedCornerShape
19 | import androidx.compose.material.icons.Icons
20 | import androidx.compose.material.icons.rounded.Cancel
21 | import androidx.compose.material.icons.rounded.Public
22 | import androidx.compose.material.icons.rounded.Refresh
23 | import androidx.compose.material3.CircularProgressIndicator
24 | import androidx.compose.material3.Divider
25 | import androidx.compose.material3.ExperimentalMaterial3Api
26 | import androidx.compose.material3.ExtendedFloatingActionButton
27 | import androidx.compose.material3.FabPosition
28 | import androidx.compose.material3.FloatingActionButton
29 | import androidx.compose.material3.Icon
30 | import androidx.compose.material3.IconButton
31 | import androidx.compose.material3.ListItem
32 | import androidx.compose.material3.ListItemDefaults
33 | import androidx.compose.material3.MaterialTheme
34 | import androidx.compose.material3.Scaffold
35 | import androidx.compose.material3.SnackbarHost
36 | import androidx.compose.material3.SnackbarHostState
37 | import androidx.compose.material3.Text
38 | import androidx.compose.runtime.Composable
39 | import androidx.compose.runtime.LaunchedEffect
40 | import androidx.compose.runtime.collectAsState
41 | import androidx.compose.runtime.getValue
42 | import androidx.compose.runtime.remember
43 | import androidx.compose.ui.Alignment
44 | import androidx.compose.ui.Modifier
45 | import androidx.compose.ui.draw.clip
46 | import androidx.compose.ui.unit.dp
47 | import com.vungn.bluetoothchat.data.BluetoothData
48 | import com.vungn.bluetoothchat.vm.BluetoothViewModel
49 |
50 | @SuppressLint("MissingPermission")
51 | @OptIn(ExperimentalMaterial3Api::class)
52 | @Composable
53 | fun Home(
54 | modifier: Modifier = Modifier, viewModel: BluetoothViewModel, navigateToChat: () -> Unit
55 | ) {
56 | val data by viewModel.data.collectAsState(initial = BluetoothData())
57 | val errorMessage by viewModel.errorMessage.collectAsState()
58 | val backgroundColor = if (isSystemInDarkTheme()) MaterialTheme.colorScheme.background
59 | else MaterialTheme.colorScheme.primary.copy(alpha = 0.05f)
60 | val listColor = if (isSystemInDarkTheme()) MaterialTheme.colorScheme.primary.copy(alpha = 0.05f)
61 | else MaterialTheme.colorScheme.background
62 | val snackBarHostState = remember { SnackbarHostState() }
63 | LaunchedEffect(key1 = true, block = {
64 | viewModel.scanBluetooth()
65 | })
66 | LaunchedEffect(key1 = errorMessage, block = {
67 | if (errorMessage != null) {
68 | snackBarHostState.showSnackbar(errorMessage.toString())
69 | }
70 | })
71 | LaunchedEffect(key1 = data.isConnected, block = {
72 | if (data.isConnected) {
73 | navigateToChat()
74 | }
75 | })
76 |
77 | if (data.isConnecting) {
78 | Scaffold(
79 | modifier = modifier.fillMaxSize(), floatingActionButton = {
80 | FloatingActionButton(
81 | onClick = { viewModel.disconnect() },
82 | shape = MaterialTheme.shapes.small.copy(all = CornerSize(50.dp)),
83 | containerColor = MaterialTheme.colorScheme.error,
84 | contentColor = MaterialTheme.colorScheme.onError
85 | ) {
86 | Icon(
87 | imageVector = Icons.Rounded.Cancel, contentDescription = "Cancel connection"
88 | )
89 | }
90 | }, floatingActionButtonPosition = FabPosition.Center
91 | ) { paddingValues ->
92 | Box(
93 | modifier = modifier
94 | .fillMaxSize()
95 | .padding(paddingValues),
96 | contentAlignment = Alignment.Center
97 | ) {
98 | Column(
99 | modifier = modifier,
100 | horizontalAlignment = Alignment.CenterHorizontally,
101 | verticalArrangement = Arrangement.spacedBy(20.dp)
102 | ) {
103 | Text(text = "Waiting for a client ...")
104 | CircularProgressIndicator()
105 | }
106 | }
107 |
108 | }
109 | } else {
110 | Scaffold(modifier = modifier.fillMaxSize(), floatingActionButton = {
111 | ExtendedFloatingActionButton(onClick = { viewModel.launchServer() },
112 | text = { Text(modifier = Modifier, text = "Launch server") },
113 | icon = { Icon(imageVector = Icons.Rounded.Public, contentDescription = null) })
114 | }, floatingActionButtonPosition = FabPosition.End, snackbarHost = {
115 | SnackbarHost(hostState = snackBarHostState)
116 | }) { paddingValues ->
117 | Column(
118 | modifier = Modifier
119 | .fillMaxSize()
120 | .padding(paddingValues)
121 | .background(backgroundColor)
122 | ) {
123 | Spacer(modifier = Modifier.padding(20.dp))
124 | Text(
125 | modifier = Modifier.padding(10.dp),
126 | text = "Paired devices",
127 | style = MaterialTheme.typography.titleLarge
128 | )
129 | LazyColumn(
130 | modifier = Modifier
131 | .padding(20.dp)
132 | .clip(RoundedCornerShape(20.dp))
133 | ) {
134 | itemsIndexed(data.pairedDevices.toList()) { index, pairedDevice ->
135 | Column(
136 | modifier = Modifier
137 | .fillMaxWidth()
138 | .background(listColor)
139 | ) {
140 | ListItem(modifier = Modifier
141 | .background(listColor)
142 | .clickable { viewModel.connectToServer(pairedDevice) },
143 | colors = ListItemDefaults.colors(containerColor = listColor),
144 | headlineText = { Text(text = pairedDevice.name ?: "Unknown name") },
145 | supportingText = { Text(text = pairedDevice.address) })
146 | if (index < data.pairedDevices.size - 1) {
147 | Divider(
148 | modifier = Modifier
149 | .fillMaxWidth()
150 | .padding(horizontal = 10.dp)
151 | )
152 | }
153 | }
154 | }
155 | }
156 | Row(
157 | modifier = Modifier
158 | .fillMaxWidth()
159 | .padding(horizontal = 10.dp),
160 | horizontalArrangement = Arrangement.SpaceBetween,
161 | verticalAlignment = Alignment.CenterVertically
162 | ) {
163 | Text(
164 | modifier = Modifier,
165 | text = "Scanned devices",
166 | style = MaterialTheme.typography.titleLarge
167 | )
168 |
169 | IconButton(onClick = { viewModel.refresh() }) {
170 | Icon(
171 | imageVector = Icons.Rounded.Refresh,
172 | tint = MaterialTheme.colorScheme.primary,
173 | contentDescription = "Refresh scanned devices"
174 | )
175 | }
176 | }
177 | LazyColumn(
178 | modifier = Modifier
179 | .padding(20.dp)
180 | .clip(RoundedCornerShape(20.dp))
181 | ) {
182 | itemsIndexed(data.scannedDevices.toList()) { index, scannedDevice ->
183 | Column(
184 | modifier = Modifier
185 | .fillMaxWidth()
186 | .background(listColor)
187 | ) {
188 | ListItem(modifier = Modifier
189 | .background(listColor)
190 | .clickable { viewModel.connectToServer(scannedDevice) },
191 | colors = ListItemDefaults.colors(containerColor = listColor),
192 | headlineText = {
193 | Text(
194 | text = scannedDevice.name ?: "Unknown name"
195 | )
196 | },
197 | supportingText = { Text(text = scannedDevice.address) })
198 | if (index < data.scannedDevices.size - 1) {
199 | Divider(
200 | modifier = Modifier
201 | .fillMaxWidth()
202 | .padding(horizontal = 10.dp)
203 | )
204 | }
205 | }
206 | }
207 | }
208 | }
209 | }
210 | }
211 | }
--------------------------------------------------------------------------------