import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Declare the three buttons from the layout file
val btnOn = findViewById(R.id.btnOn)
val btnOff = findViewById(R.id.btnOFF)
val btnDisc = findViewById(R.id.btnDiscoverable)
// Initialize the Bluetooth Adapter
val bAdapter = BluetoothAdapter.getDefaultAdapter()
// Action when Turn ON Button is clicked
btnOn.setOnClickListener {
// If Bluetooth support or API is absent or private in the device
if (bAdapter == null) {
Toast.makeText(applicationContext, "Bluetooth Not Supported", Toast.LENGTH_SHORT).show()
} else {
// Turn ON the Bluetooth using an Intent and making a Toast Message
if (!bAdapter.isEnabled) {
startActivityForResult(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1)
Toast.makeText(applicationContext, "Bluetooth Turned ON", Toast.LENGTH_SHORT).show()
}
}
}
// Action when Turn OFF Button is clicked
btnOff.setOnClickListener {
// Disable the Bluetooth Adapter and make a Toast
bAdapter!!.disable()
Toast.makeText(applicationContext, "Bluetooth Turned OFF", Toast.LENGTH_SHORT).show()
}
// Action when Discoverable Button is clicked
btnDisc.setOnClickListener {
// Make the Bluetooth in a Discovering State and make a Toast
if (!bAdapter!!.isDiscovering) {
startActivityForResult(Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 1)
Toast.makeText(applicationContext, "Making Device Discoverable", Toast.LENGTH_SHORT).show()
}
}
}
}