Article 103 | Moiks Developer Blog | Advanced Android Development
Android offers several technologies for exchanging data between nearby devices. In our previous tutorials, we explored Bluetooth Low Energy (BLE), Wi-Fi Direct, and Google’s Nearby Connections API.
But what if you want to build an offline file-sharing application using Bluetooth Classic, without depending on Wi-Fi, internet access, a backend server, or Google Play services?
Bluetooth Classic supports persistent connections and bidirectional byte streams through RFCOMM sockets, making it suitable for transferring documents, small photos, messages, and other files between compatible Android devices.
In this comprehensive tutorial, we’ll build the foundations of a Bluetooth Classic file-sharing application using Kotlin, Jetpack Compose, BluetoothSocket, BluetoothServerSocket, Kotlin Coroutines, StateFlow, and MVVM architecture.
We’ll cover device discovery, pairing, RFCOMM connections, file transfer protocols, progress tracking, secure storage, Android permissions, error handling, and testing on physical devices.
1. What Is Android Bluetooth Classic?
Bluetooth Classic is a wireless communication technology designed for continuous device-to-device communication.
Unlike Bluetooth Low Energy, which is optimized for small data exchanges and low power consumption, Bluetooth Classic provides stream-oriented connections suitable for sustained communication.
Android exposes Bluetooth Classic functionality through APIs including:
BluetoothAdapterBluetoothDeviceBluetoothSocketBluetoothServerSocketBluetoothManager
These APIs allow applications to discover nearby Bluetooth devices, establish connections, and exchange bytes through input and output streams.
2. Bluetooth Classic vs Bluetooth Low Energy
Understanding the difference helps you choose the right technology.
| Feature | Bluetooth Classic | Bluetooth LE |
|---|---|---|
| Communication | Stream-oriented RFCOMM and other profiles | GATT services and characteristics |
| Common use cases | Audio, serial communication, file transfer | Sensors, wearables, IoT |
| Data exchange | Continuous byte streams | Attribute-based operations |
| File transfers | Possible using custom RFCOMM protocol | Possible but typically less convenient |
| Power optimization | Depends on connection behavior | Designed for low-power use |
| Android APIs | BluetoothSocket | BluetoothGatt |
Bluetooth Classic is generally more suitable for our custom socket-based file transfer example.
However, actual throughput depends on device hardware, radio conditions, and implementation.
3. Bluetooth Classic vs Wi-Fi Direct vs Nearby Connections
We’ve already covered Wi-Fi Direct and Nearby Connections in Articles 101 and 102.
Here’s how our new implementation differs.
| Technology | Transport API | Google Play services |
|---|---|---|
| Bluetooth Classic | RFCOMM sockets | Not required |
| Wi-Fi Direct | Wi-Fi P2P and TCP sockets | Not required |
| Nearby Connections | ConnectionsClient and Payload | Required |
Bluetooth Classic can be a useful fallback for devices where Wi-Fi-based sharing is unavailable or unnecessary.
It is not necessarily the fastest option for large videos or multi-gigabyte transfers.
4. What Will We Build?
Our sample project will be called Bluetooth File Share Demo.
The application will support:
- Checking Bluetooth availability.
- Requesting Bluetooth enablement.
- Discovering nearby Bluetooth Classic devices.
- Displaying paired devices.
- Establishing a secure RFCOMM connection.
- Accepting incoming connections.
- Selecting files from device storage.
- Sending files using output streams.
- Receiving files using input streams.
- Tracking file transfer progress.
- Canceling transfers.
- Handling disconnections and errors.
The tutorial focuses on the core implementation. A complete production application also needs lifecycle management, protocol validation, and comprehensive device testing.
5. Recommended Technology Stack
| Component | Technology |
|---|---|
| Language | Kotlin |
| UI | Jetpack Compose + Material 3 |
| Architecture | MVVM |
| Communication | Bluetooth Classic RFCOMM |
| Concurrency | Kotlin Coroutines |
| State | StateFlow |
| File selection | Storage Access Framework |
| Storage | App-specific files |
| Dependency injection | Hilt (optional) |
| Testing | JUnit and physical Android devices |
6. Create the Android Project
Create an Empty Activity project in Android Studio with Kotlin and Jetpack Compose.
Suggested package:
com.moiks.bluetoothfileshare
Organize the source code:
com.moiks.bluetoothfileshare
│
├── data
│ ├── bluetooth
│ │ ├── BluetoothConnectionManager.kt
│ │ ├── BluetoothDiscoveryManager.kt
│ │ └── BluetoothFileTransfer.kt
│ └── repository
│ └── BluetoothRepository.kt
│
├── domain
│ └── model
│ ├── BluetoothDeviceUi.kt
│ ├── ConnectionState.kt
│ └── FileTransferState.kt
│
├── presentation
│ ├── BluetoothViewModel.kt
│ └── BluetoothScreen.kt
│
└── MainActivity.kt
This separation prevents the Compose UI from directly managing Bluetooth sockets.
7. Understand RFCOMM Communication
RFCOMM provides a serial-port-like byte stream over Bluetooth Classic.
The communication model resembles a TCP client/server connection.
Android Device A Android Device B
| |
BluetoothServerSocket |
| |
| <------ Connection request -------|
| |
BluetoothSocket BluetoothSocket
| |
InputStream <------------------- OutputStream
OutputStream -------------------> InputStream
Once connected, both devices can exchange data through their socket streams.
RFCOMM does not define your application’s file format or transfer protocol. You must implement those yourself.
8. Android Bluetooth Permissions
Bluetooth permissions differ across Android versions.
For Android 12 and later, applications targeting Android 12 or higher generally use the nearby-device runtime permissions:
BLUETOOTH_SCANBLUETOOTH_CONNECTBLUETOOTH_ADVERTISE, if your app needs to advertise or make the device discoverable
For older Android versions, legacy Bluetooth permissions and location permissions may be necessary for discovery.
A representative manifest configuration is:
<uses-feature
android:name="android.hardware.bluetooth"
android:required="false" />
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation" />
<uses-permission
android:name="android.permission.BLUETOOTH_CONNECT" />
Only use neverForLocation if your application can truthfully assert that Bluetooth scan results are not used to derive physical location. This flag can affect the availability of some Bluetooth scan results.
For older devices, review the Android documentation for the exact location-permission requirements of your target SDK and supported API levels.
9. Request Runtime Permissions
Use the Activity Result API.
val permissionLauncher =
rememberLauncherForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { results ->
val granted = results.values.all { it }
if (granted) {
// Begin Bluetooth operations.
} else {
// Explain unavailable functionality.
}
}
On Android 12+, build the permission request list according to the operations you actually perform.
For example, discovery and connection typically require both scan and connect permissions.
Do not request unrelated permissions merely because Bluetooth is involved.
10. Check Bluetooth Hardware Availability
Some Android devices do not support Bluetooth Classic.
Use BluetoothManager:
val bluetoothManager =
context.getSystemService(
BluetoothManager::class.java
)
val bluetoothAdapter =
bluetoothManager.adapter
if (bluetoothAdapter == null) {
// Bluetooth is unavailable.
}
Avoid assuming every Android TV, tablet, emulator, or specialized Android device supports RFCOMM.
11. Request Bluetooth Enablement
Applications should not silently enable Bluetooth.
Instead, request user approval:
val enableBluetoothLauncher =
rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
// Recheck adapter state and permissions.
}
Launch the system request:
val intent =
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
enableBluetoothLauncher.launch(intent)
The operation requires appropriate Bluetooth permissions on newer Android versions.
The user may decline, so always handle that outcome.
12. Understand Bluetooth Device Discovery
Bluetooth Classic discovery searches for nearby discoverable Bluetooth devices.
Use:
bluetoothAdapter.startDiscovery()
This operation requires the relevant permissions.
Discovery is asynchronous. Devices are reported through Android broadcasts.
Starting discovery does not guarantee that every nearby Bluetooth device will appear.
A device may be undiscoverable, out of range, or incompatible.
13. Receive Discovered Devices
Register a BroadcastReceiver for Bluetooth discovery events.
val receiver = object : BroadcastReceiver() {
override fun onReceive(
context: Context,
intent: Intent
) {
if (
intent.action ==
BluetoothDevice.ACTION_FOUND
) {
val device =
if (Build.VERSION.SDK_INT >= 33) {
intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE,
BluetoothDevice::class.java
)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE
)
}
device?.let {
// Add discovered device to state.
}
}
}
}
Register the receiver with the appropriate IntentFilter, lifecycle, and exported/not-exported behavior for the Android version.
Unregister it when discovery is no longer needed.
14. Stop Bluetooth Discovery
Bluetooth discovery is resource-intensive and may interfere with connection performance.
Before connecting:
bluetoothAdapter.cancelDiscovery()
Also stop discovery when the user exits the scanning screen or explicitly cancels scanning.
Avoid continuously scanning in the background without a clear product requirement.
15. Get Previously Paired Devices
Previously bonded devices can be retrieved using:
val pairedDevices =
bluetoothAdapter.bondedDevices
On Android 12+, accessing bonded-device information requires BLUETOOTH_CONNECT.
Displaying paired devices first can improve the user experience because users may not need to repeat discovery.
16. Create a Device UI Model
Avoid passing raw BluetoothDevice objects throughout the UI.
data class BluetoothDeviceUi(
val address: String,
val name: String,
val isBonded: Boolean
)
Keep the actual Bluetooth device references inside the Bluetooth manager or repository.
A Bluetooth address is sensitive device information. Do not log or upload it unnecessarily.
17. Display Devices with Jetpack Compose
@Composable
fun BluetoothDeviceList(
devices: List<BluetoothDeviceUi>,
onConnect: (BluetoothDeviceUi) -> Unit
) {
LazyColumn {
items(
items = devices,
key = { it.address }
) { device ->
ListItem(
headlineContent = {
Text(device.name)
},
supportingContent = {
Text(
if (device.isBonded)
"Paired device"
else
"Nearby device"
)
},
trailingContent = {
Button(
onClick = {
onConnect(device)
}
) {
Text("Connect")
}
}
)
}
}
}
The interface should distinguish scanning, connecting, connected, and disconnected states.
18. Understand Bluetooth Pairing
Pairing and RFCOMM connection are related but separate operations.
Pairing establishes a trusted relationship between devices through the operating system’s Bluetooth security mechanisms.
A secure RFCOMM connection may initiate a pairing dialog if the devices are not already bonded.
Your application should allow Android to manage system pairing and never attempt to bypass user approval.
19. Use a Shared Service UUID
RFCOMM clients and servers must agree on the same service UUID.
For example:
private val FILE_TRANSFER_UUID =
UUID.fromString(
"e57d6d0c-7f45-4d5b-a31c-4ad7e8298c01"
)
This example UUID identifies the application’s file-transfer service.
Both devices must use the same value.
The UUID is a service identifier, not an encryption key or secret.
For your own application, generate a stable UUID and use it consistently across releases.
20. Create a Bluetooth RFCOMM Server
The receiving device listens for incoming connections.
class BluetoothServer(
private val adapter: BluetoothAdapter
) {
fun listen(): BluetoothSocket? {
val serverSocket =
adapter.listenUsingRfcommWithServiceRecord(
"Moiks File Transfer",
FILE_TRANSFER_UUID
)
return try {
serverSocket.accept()
} finally {
serverSocket.close()
}
}
}
accept() blocks until a connection arrives or the socket closes.
Never call it on the main thread.
Run the server on an I/O dispatcher and provide a cancellation mechanism that closes the listening socket.
21. Connect as an RFCOMM Client
The sending device initiates a connection.
fun connect(
adapter: BluetoothAdapter,
device: BluetoothDevice
): BluetoothSocket {
adapter.cancelDiscovery()
val socket =
device.createRfcommSocketToServiceRecord(
FILE_TRANSFER_UUID
)
try {
socket.connect()
return socket
} catch (error: IOException) {
socket.close()
throw error
}
}
connect() is a blocking operation.
Run it off the main thread.
A secure RFCOMM socket uses Android’s Bluetooth security mechanisms. The application should still verify that the user selected the intended device.
22. Use Kotlin Coroutines for Connections
suspend fun connectToDevice(
adapter: BluetoothAdapter,
device: BluetoothDevice
): BluetoothSocket =
withContext(Dispatchers.IO) {
connect(adapter, device)
}
Coroutines keep blocking Bluetooth operations away from the UI thread.
However, coroutine cancellation does not automatically interrupt every blocking socket call.
Close the underlying socket when canceling a connection attempt.
23. Create a Connection State Model
sealed interface ConnectionState {
data object Disconnected : ConnectionState
data object Scanning : ConnectionState
data object Connecting : ConnectionState
data class Connected(
val deviceName: String
) : ConnectionState
data class Error(
val message: String
) : ConnectionState
}
Expose this state through StateFlow.
private val _connectionState =
MutableStateFlow<ConnectionState>(
ConnectionState.Disconnected
)
val connectionState =
_connectionState.asStateFlow()
The Compose screen can react automatically to state changes.
24. Access RFCOMM Input and Output Streams
Once connected:
val inputStream =
bluetoothSocket.inputStream
val outputStream =
bluetoothSocket.outputStream
These streams provide bidirectional byte communication.
The sending device writes bytes to its output stream.
The receiving device reads those bytes from its input stream.
Both devices can send and receive, but the application must coordinate simultaneous operations correctly.
25. Why a File Transfer Protocol Is Necessary
A Bluetooth socket transports bytes, not complete file objects.
Without an application protocol, the receiver cannot reliably determine:
- Which file is being transferred.
- Its filename.
- Its expected size.
- Where one file ends.
- Whether the transfer completed.
- Whether the received data is valid.
We therefore need a simple framing protocol.
26. Design a File Transfer Protocol
For our tutorial, use this message structure:
MAGIC NUMBER
PROTOCOL VERSION
FILENAME LENGTH
FILENAME BYTES
FILE SIZE
FILE CONTENT BYTES
A more advanced protocol could include:
TRANSFER ID
MIME TYPE
SHA-256 CHECKSUM
TRANSFER STATUS
The sender and receiver must agree on field order, byte encoding, and maximum allowed sizes.
Use a length-delimited protocol instead of depending on the connection closing to indicate file completion.
27. Use DataOutputStream
DataOutputStream helps write structured binary values.
val output =
DataOutputStream(
BufferedOutputStream(
bluetoothSocket.outputStream
)
)
For example:
output.writeInt(0x4D4F494B)
output.writeInt(1)
output.writeLong(fileSize)
The first value is an application-specific magic number.
The second is a protocol version.
The third is the expected file size.
Both devices must interpret these values identically.
28. Select a File Using Storage Access Framework
Use Android’s system document picker.
val filePicker =
rememberLauncherForActivityResult(
ActivityResultContracts.OpenDocument()
) { uri ->
uri?.let {
// Pass URI to ViewModel.
}
}
Launch:
filePicker.launch(
arrayOf("*/*")
)
This approach does not require broad storage permissions.
It also supports compatible document providers rather than only traditional filesystem paths.
29. Read File Metadata
Use ContentResolver and OpenableColumns.
data class SelectedFile(
val uri: Uri,
val name: String,
val size: Long
)
A document provider may return an unknown file size.
For this initial protocol, require a known size or copy the selected content into an application-owned temporary file to determine its exact length before transfer.
Do not blindly assume every URI exposes a valid filesystem path.
30. Implement File Sending
The following example assumes a known file size and a validated filename.
suspend fun sendFile(
context: Context,
socket: BluetoothSocket,
uri: Uri,
fileName: String,
fileSize: Long,
onProgress: (Float) -> Unit
) = withContext(Dispatchers.IO) {
require(fileSize >= 0)
val output = DataOutputStream(
BufferedOutputStream(socket.outputStream)
)
val nameBytes =
fileName.toByteArray(Charsets.UTF_8)
require(nameBytes.size in 1..1024)
output.writeInt(0x4D4F494B)
output.writeInt(1)
output.writeInt(nameBytes.size)
output.write(nameBytes)
output.writeLong(fileSize)
val input = requireNotNull(
context.contentResolver.openInputStream(uri)
)
input.use { stream ->
val buffer = ByteArray(32 * 1024)
var transferred = 0L
while (transferred < fileSize) {
val remaining = fileSize - transferred
val count = stream.read(
buffer,
0,
minOf(buffer.size.toLong(), remaining).toInt()
)
if (count == -1) {
throw EOFException(
"Source ended before expected size"
)
}
if (count == 0) continue
output.write(buffer, 0, count)
transferred += count
if (fileSize > 0L) {
onProgress(
transferred.toFloat() / fileSize
)
}
}
}
output.flush()
}
This implementation streams data in chunks rather than loading the complete file into memory.
For production use, serialize transfers on the same output stream, manage socket ownership carefully, and add a receiver acknowledgment before declaring end-to-end success.
31. Implement File Receiving
The receiver reads the protocol header, validates it, and streams the expected number of bytes to storage.
suspend fun receiveFile(
socket: BluetoothSocket,
destinationDir: File,
onProgress: (Float) -> Unit
): File = withContext(Dispatchers.IO) {
val input = DataInputStream(
BufferedInputStream(socket.inputStream)
)
require(input.readInt() == 0x4D4F494B) {
"Invalid transfer header"
}
require(input.readInt() == 1) {
"Unsupported protocol version"
}
val nameLength = input.readInt()
require(nameLength in 1..1024) {
"Invalid filename length"
}
val nameBytes = ByteArray(nameLength)
input.readFully(nameBytes)
val originalName =
String(nameBytes, Charsets.UTF_8)
val fileSize = input.readLong()
require(fileSize in 0..MAX_FILE_SIZE) {
"Invalid file size"
}
val safeName = originalName
.substringAfterLast('/')
.substringAfterLast('\\')
.replace(Regex("[^a-zA-Z0-9._-]"), "_")
.take(120)
.ifBlank { "received_file" }
destinationDir.mkdirs()
val destination = File.createTempFile(
"incoming_",
".part",
destinationDir
)
try {
FileOutputStream(destination).use { output ->
val buffer = ByteArray(32 * 1024)
var received = 0L
while (received < fileSize) {
val remaining = fileSize - received
val count = input.read(
buffer,
0,
minOf(
buffer.size.toLong(),
remaining
).toInt()
)
if (count == -1) {
throw EOFException(
"Transfer interrupted"
)
}
if (count == 0) continue
output.write(buffer, 0, count)
received += count
if (fileSize > 0L) {
onProgress(
received.toFloat() / fileSize
)
}
}
}
destination
} catch (error: Exception) {
destination.delete()
throw error
}
}
Define MAX_FILE_SIZE according to your application’s storage policy.
This example returns a temporary .part file. After validating its content and optional checksum, move it to a collision-safe final filename.
The parsed safeName should be retained as display metadata and used only after validating the destination path.
32. Understand Stream Boundaries
One of the most common socket programming mistakes is assuming that a single read() call returns the entire requested message.
It does not.
A read may return fewer bytes than requested.
For fixed-length fields, use operations such as:
input.readFully(buffer)
For file content, keep reading until the declared byte count has been received.
Never treat a short read as the end of a file.
33. Create Transfer Progress State
sealed interface FileTransferState {
data object Idle : FileTransferState
data class Sending(
val progress: Float
) : FileTransferState
data class Receiving(
val progress: Float
) : FileTransferState
data object Completed : FileTransferState
data class Failed(
val message: String
) : FileTransferState
}
Use a MutableStateFlow inside the repository or transfer manager.
Progress values should remain between 0f and 1f.
34. Display Progress with Compose
@Composable
fun FileTransferProgress(
state: FileTransferState
) {
when (state) {
FileTransferState.Idle -> {
Text("Ready to transfer")
}
is FileTransferState.Sending -> {
Column {
Text("Sending file...")
LinearProgressIndicator(
progress = {
state.progress.coerceIn(0f, 1f)
}
)
}
}
is FileTransferState.Receiving -> {
Column {
Text("Receiving file...")
LinearProgressIndicator(
progress = {
state.progress.coerceIn(0f, 1f)
}
)
}
}
FileTransferState.Completed -> {
Text("Transfer completed")
}
is FileTransferState.Failed -> {
Text(state.message)
}
}
}
For better accessibility, expose progress descriptions to assistive technologies.
35. Avoid Excessive Progress Updates
Updating Compose state for every small chunk can generate unnecessary UI work.
For example, update the visible progress when:
- At least 100 milliseconds have elapsed, or
- The percentage has changed significantly, or
- The transfer reaches completion.
Keep actual transfer counters separate from throttled UI updates.
36. Calculate File Transfer Speed
Track the change in transferred bytes over elapsed time.
fun calculateSpeed(
bytesTransferred: Long,
elapsedSeconds: Double
): Double {
if (elapsedSeconds <= 0.0) return 0.0
return bytesTransferred / elapsedSeconds
}
Display a human-readable value:
125 KB/s
850 KB/s
1.4 MB/s
These are display examples, not guaranteed Bluetooth Classic speeds.
Actual throughput varies considerably.
37. Estimate Remaining Time
Calculate an approximate ETA:
fun calculateEta(
remainingBytes: Long,
bytesPerSecond: Double
): Long? {
if (bytesPerSecond <= 0.0) {
return null
}
return (
remainingBytes / bytesPerSecond
).toLong()
}
Use a moving average to avoid displaying wildly fluctuating estimates.
38. Implement Transfer Cancellation
An active transfer may be canceled by the user.
Your transfer manager should:
- Mark the transfer as canceled.
- Stop reading or writing.
- Close the relevant socket when necessary to unblock I/O.
- Delete incomplete temporary files.
- Update the UI.
Closing a socket generally terminates the current connection, so reconnect if another transfer is needed.
A more advanced application can implement protocol-level cancellation without always closing the connection.
39. Handle Socket Disconnections
A Bluetooth connection can be lost when:
- A device moves out of range.
- Bluetooth is disabled.
- The remote application closes.
- The operating system terminates a process.
- Wireless interference occurs.
- A socket operation fails.
Handle IOException and update the connection state.
Do not assume a socket remains connected indefinitely after a successful initial connection.
40. Validate Received Files
A successful byte transfer does not guarantee that the content is safe or correct.
For improved integrity, calculate a SHA-256 digest on the sender and receiver.
Example:
val digest =
MessageDigest.getInstance("SHA-256")
Update the digest while streaming the file.
Compare the final digest with an expected value supplied through your protocol.
A checksum detects accidental corruption, but it does not replace authenticated device identity or protect against malicious content.
41. File Transfer Security
Use secure RFCOMM sockets for normal file sharing.
Avoid insecure socket APIs unless your product has a specific, justified interoperability requirement.
Additional security recommendations:
- Require user selection of the destination device.
- Show pairing and connection status clearly.
- Ask for approval before receiving unexpected files.
- Validate incoming metadata.
- Enforce file-size limits.
- Prevent path traversal.
- Store incoming files in app-controlled directories.
- Never automatically execute or open received files.
- Avoid exposing received files to other applications without user intent.
Treat remote filenames, MIME types, and declared sizes as untrusted.
42. Avoid Arbitrary File System Access
Use the Storage Access Framework for sending.
For receiving, use app-specific storage or let the user select a destination through ACTION_CREATE_DOCUMENT.
Do not request MANAGE_EXTERNAL_STORAGE for a normal Bluetooth file-sharing app.
If the user wants to export a received file, use a supported document creation or sharing flow.
43. Implement the Repository Interface
interface BluetoothRepository {
val devices:
StateFlow<List<BluetoothDeviceUi>>
val connectionState:
StateFlow<ConnectionState>
val transferState:
StateFlow<FileTransferState>
fun startDiscovery()
fun stopDiscovery()
suspend fun connect(address: String)
suspend fun sendFile(uri: Uri)
fun disconnect()
}
The repository hides the low-level Bluetooth implementation from the ViewModel.
It also provides a convenient boundary for unit testing.
44. Create the ViewModel
class BluetoothViewModel(
private val repository: BluetoothRepository
) : ViewModel() {
val devices = repository.devices
val connectionState =
repository.connectionState
val transferState =
repository.transferState
fun scan() {
repository.startDiscovery()
}
fun connect(address: String) {
viewModelScope.launch {
repository.connect(address)
}
}
fun sendFile(uri: Uri) {
viewModelScope.launch {
repository.sendFile(uri)
}
}
fun disconnect() {
repository.disconnect()
}
}
Use Hilt or a custom ViewModel factory to provide the repository.
A real implementation should expose failures and loading states rather than allowing uncaught exceptions to escape from launched coroutines.
45. Collect State in Jetpack Compose
@Composable
fun BluetoothScreen(
viewModel: BluetoothViewModel
) {
val devices by
viewModel.devices.collectAsStateWithLifecycle()
val connection by
viewModel.connectionState
.collectAsStateWithLifecycle()
val transfer by
viewModel.transferState
.collectAsStateWithLifecycle()
Column {
Button(onClick = viewModel::scan) {
Text("Find Bluetooth Devices")
}
BluetoothDeviceList(
devices = devices,
onConnect = {
viewModel.connect(it.address)
}
)
FileTransferProgress(transfer)
}
}
Add the appropriate lifecycle Compose dependency to use collectAsStateWithLifecycle().
46. Recommended Premium UI/UX
A polished Bluetooth file-sharing app can use five main screens.
Home: Bluetooth status, local device information, Send Files and Receive Files actions.
Device Discovery: Paired devices, nearby devices, scan indicator, and connection buttons.
Connection Screen: Selected device name, pairing status, and connection feedback.
Transfer Screen: Filename, progress bar, speed, estimated time, and Cancel button.
Transfer Complete: Success message, saved file details, Open File and Share Again actions.
Use Material 3 components and support both light and dark themes.
47. Support Multiple File Transfers
The basic example sends one file at a time.
To support multiple files, introduce a transfer queue:
data class TransferItem(
val id: String,
val uri: Uri,
val name: String,
val status: TransferStatus
)
Serialize file transfers over a single RFCOMM connection unless your protocol explicitly supports multiplexing.
Add message framing between files so the receiver can distinguish each transfer.
48. Handle Empty Files
A file can legitimately contain zero bytes.
Your protocol should support a declared size of zero.
Avoid dividing by zero when calculating progress.
For empty files, transfer the header, create an empty destination file, and complete the operation after the receiver validates the message.
49. Handle Large Files
For large files:
- Stream data instead of loading it into memory.
- Check available destination storage.
- Use bounded buffers.
- Enforce application-defined size limits.
- Avoid blocking the main thread.
- Handle interruption and cleanup.
- Consider whether Wi-Fi Direct would offer a better user experience.
Bluetooth Classic can transfer files, but it may not be the best primary transport for very large videos.
50. Manage Background Transfers
A ViewModel does not guarantee that a transfer survives process termination.
For transfers that must continue while the app is not visible, evaluate a foreground service with an appropriate service type, permission configuration, and user-visible notification.
Android foreground-service and background-start restrictions vary by OS version.
Do not assume a foreground service can always be started from the background.
51. Optimize Battery Usage
Bluetooth discovery can consume power.
Best practices include:
- Stop discovery after selecting a device.
- Avoid repeated scans when unnecessary.
- Close unused sockets.
- Stop listening when the receiving feature is disabled.
- Avoid excessive progress updates.
- Release resources after transfer completion.
Measure battery behavior on actual devices.
52. Test on Physical Android Devices
Use at least two Bluetooth Classic-compatible Android devices.
Test the following:
| Scenario | Expected result |
|---|---|
| Bluetooth disabled | Enable prompt shown |
| Permission denied | Clear explanation |
| No nearby devices | Empty state displayed |
| Paired device found | Device appears in list |
| New device selected | Pairing/connection handled |
| Connection rejected | Recoverable error |
| Small document transfer | Successful receipt |
| Large file transfer | Stable streaming and progress |
| Receiver disconnects | Sender handles failure |
| Transfer canceled | Partial file cleaned up |
| Duplicate filename | No unintended overwrite |
| Insufficient storage | Safe failure |
Bluetooth emulators are not a substitute for physical device testing.
53. Common Bluetooth Errors
Connection refused
Possible causes include an incorrect service UUID, no active server listener, pairing problems, or incompatible devices.
Discovery returns no devices
Check permissions, Bluetooth state, discoverability, device range, and discovery lifecycle.
File transfer stops unexpectedly
Check socket exceptions, remote process lifecycle, device range, and incomplete file cleanup.
Permission exception
Verify the Android version, target SDK, manifest declarations, and runtime permission state.
File cannot be opened
The selected URI may no longer be accessible, or the document provider may reject the operation.
Use the Storage Access Framework correctly and preserve URI access where necessary.
54. Unit Testing Strategy
Mock or fake the repository to test ViewModel behavior without physical Bluetooth hardware.
Test:
- Discovery state transitions.
- Connection state updates.
- Transfer progress calculations.
- Error propagation.
- Cancellation state.
- Filename validation.
- Protocol header parsing.
Keep the binary protocol encoder and decoder in independent classes so they can be tested using in-memory streams.
55. Integration Testing Strategy
Integration testing requires physical devices.
Verify:
- Secure RFCOMM connection setup.
- Correct UUID usage.
- Pairing behavior.
- Byte-stream framing.
- Exact transferred file size.
- Checksum validation.
- Recovery from interrupted transfers.
- Cleanup after cancellation.
Compare received files against the originals using SHA-256.
56. Can Bluetooth Classic File Sharing Work on iOS?
Not as a general cross-platform RFCOMM solution.
Apple restricts access to Bluetooth Classic communication through supported frameworks and accessory programs. A custom Android RFCOMM file-sharing protocol cannot be assumed to work with an ordinary iPhone application.
For Android-to-iOS file sharing, consider other cross-platform transport approaches, subject to platform capabilities and permissions.
57. Can This Be Built with Flutter?
Yes, Flutter can provide the UI while native Android Kotlin handles Bluetooth Classic RFCOMM communication through platform channels or a compatible plugin.
However, plugin support varies, and iOS restrictions still apply.
For Android-only Bluetooth Classic file sharing, native Kotlin provides direct access to the Android Bluetooth APIs.
58. Production Checklist
Before publishing:
- Verify Bluetooth Classic hardware support.
- Implement version-specific Bluetooth permissions.
- Handle Bluetooth enablement through system UI.
- Display paired and discovered devices.
- Stop discovery before connecting.
- Use secure RFCOMM sockets.
- Keep socket I/O off the main thread.
- Define a validated transfer protocol.
- Stream files using bounded buffers.
- Show accurate transfer progress.
- Handle cancellation and disconnection.
- Sanitize incoming filenames.
- Validate file size and integrity.
- Clean up temporary files.
- Test on multiple physical devices.
59. Official Android Documentation
For current implementation guidance, refer to:
- Android Bluetooth Overview
- Find Bluetooth Devices
- Connect Bluetooth Devices
- Transfer Bluetooth Data
- Bluetooth Permissions
- Android Storage Access Framework
- Jetpack Compose Documentation
60. Conclusion
Bluetooth Classic remains a useful technology for building offline Android device-to-device communication features.
By combining Kotlin, Jetpack Compose, secure RFCOMM sockets, Coroutines, StateFlow, and MVVM, you can implement a custom file-sharing workflow without requiring internet access, Wi-Fi Direct, or Google Play services.
The most important concepts are secure device connections, reliable byte-stream framing, safe file storage, progress tracking, and proper resource cleanup.
The code examples in this tutorial illustrate the essential building blocks. They are not a complete drop-in application; production use requires integrating the server and client lifecycles, permissions, transfer protocol, error handling, and cancellation into a tested implementation.
With these foundations, you can build Bluetooth-based document sharing, offline communication utilities, and custom device-to-device data exchange applications.
Continue learning advanced Android development with Moiks Developer Blog.
© Moiks Developer Blog — Android Development Tutorials