0% found this document useful (0 votes)
11 views4 pages

K

The document is a Kotlin implementation of an Android application that manages Bluetooth connections and interactions. It includes functionality for enabling Bluetooth, listing paired devices, sending commands, and receiving data automatically. The app also features a user interface with buttons for automatic and manual control, as well as handling Bluetooth permissions at runtime.

Uploaded by

eyedy2023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

K

The document is a Kotlin implementation of an Android application that manages Bluetooth connections and interactions. It includes functionality for enabling Bluetooth, listing paired devices, sending commands, and receiving data automatically. The app also features a user interface with buttons for automatic and manual control, as well as handling Bluetooth permissions at runtime.

Uploaded by

eyedy2023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

package com.example.

suhailcontrol

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.coroutines.*
import java.io.InputStream
import java.io.OutputStream
import java.util.*

class MainActivity : AppCompatActivity() {

private lateinit var bluetoothAdapter: BluetoothAdapter


private lateinit var deviceListAdapter: ArrayAdapter<String>
private var bluetoothSocket: BluetoothSocket? = null
private var outputStream: OutputStream? = null
private var inputStream: InputStream? = null

private val uuid: UUID = UUID.fromString("00001101-0000-1000-8000-


00805F9B34FB")

// Request permissions on runtime


private val requestPermissionsLauncher =

registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions())
{ permissions ->
if (permissions[android.Manifest.permission.BLUETOOTH_CONNECT] == true
&&
permissions[android.Manifest.permission.BLUETOOTH_SCAN] == true
) {
setupBluetooth()
} else {
Toast.makeText(this, "Permissions are required for Bluetooth
functionality", Toast.LENGTH_LONG).show()
}
}

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val btnEnableBluetooth: Button = findViewById(R.id.btnEnableBluetooth)
val deviceList: ListView = findViewById(R.id.deviceList)
val btnSendCommand: Button = findViewById(R.id.btnSendCommand)
val dataDisplay: TextView = findViewById(R.id.dataDisplay)
val smartInterface: LinearLayout = findViewById(R.id.smartInterface)
btnEnableBluetooth.setOnClickListener {
if (bluetoothAdapter.isEnabled) {
Toast.makeText(this, "Bluetooth is already enabled",
Toast.LENGTH_SHORT).show()
} else {
requestPermissions()
}
}

val pairedDevices: Set<BluetoothDevice> = bluetoothAdapter.bondedDevices


val deviceListNames = ArrayList<String>()
pairedDevices.forEach { device ->
deviceListNames.add("${device.name} - ${device.address}")
}

deviceListAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1,


deviceListNames)
deviceList.adapter = deviceListAdapter

btnSendCommand.setOnClickListener {
sendData("1") // Customize the command to be sent
}

startAutomaticDataReceiving()
setupSmartInterface(smartInterface)
}

private fun requestPermissions() {


val permissionsNeeded = mutableListOf(
android.Manifest.permission.BLUETOOTH_CONNECT,
android.Manifest.permission.BLUETOOTH_SCAN,
android.Manifest.permission.ACCESS_FINE_LOCATION
)

val missingPermissions = permissionsNeeded.filter {


ContextCompat.checkSelfPermission(this, it) !=
PackageManager.PERMISSION_GRANTED
}

if (missingPermissions.isNotEmpty()) {
requestPermissionsLauncher.launch(missingPermissions.toTypedArray())
} else {
setupBluetooth()
}
}

private fun setupBluetooth() {


if (!bluetoothAdapter.isEnabled) {
bluetoothAdapter.enable()
}

val pairedDevices: Set<BluetoothDevice> = bluetoothAdapter.bondedDevices


val deviceListNames = ArrayList<String>()
pairedDevices.forEach { device ->
deviceListNames.add("${device.name} - ${device.address}")
}

deviceListAdapter.clear()
deviceListAdapter.addAll(deviceListNames)
}

private fun sendData(data: String) {


outputStream?.write(data.toByteArray())
Toast.makeText(this, "Data sent", Toast.LENGTH_SHORT).show()
}

private fun startAutomaticDataReceiving() {


GlobalScope.launch(Dispatchers.IO) {
val buffer = ByteArray(1024)
var bytes: Int
while (true) {
try {
bytes = inputStream?.read(buffer) ?: break
val receivedData = String(buffer, 0, bytes)

withContext(Dispatchers.Main) {
findViewById<TextView>(R.id.dataDisplay).text =
receivedData
}

analyzeAndActOnData(receivedData)

} catch (e: Exception) {


e.printStackTrace()
break
}
}
}
}

private fun analyzeAndActOnData(data: String) {


when (data.trim()) {
"HIGH_TEMP" -> sendData("‫)"خفض الحرارة‬
"LOW_BATTERY" -> sendData("‫)"اشحن البطارية‬
// Add more conditions as needed
}
}

private fun setupSmartInterface(smartInterface: LinearLayout) {


val buttonAutomatic = Button(this).apply {
text = "‫"تفعيل التحكم التلقائي‬
setOnClickListener {
Toast.makeText(this@MainActivity, "‫"تم تفعيل التحكم التلقائي‬,
Toast.LENGTH_SHORT).show()
}
}

val buttonManual = Button(this).apply {


text = "‫"تفعيل التحكم اليدوي‬
setOnClickListener {
Toast.makeText(this@MainActivity, "‫"تم تفعيل التحكم اليدوي‬,
Toast.LENGTH_SHORT).show()
}
}

smartInterface.addView(buttonAutomatic)
smartInterface.addView(buttonManual)
}
}

You might also like