Turn On/Off Bluetooth in android in Kotlin
By Super Admin |
Jul 09, 2021 |
Laravel
How to enable/disable bluetooth in android in Kotlin.
In the activity xml file (activity_main.xml), add two buttons and change the text and id as given below.
<Button
android:id="@+id/btnBluetoothOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On Bluetooth"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.692" />
<Button
android:id="@+id/btnBluetoothOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Off Bluetooth"
android:textColor="@color/white"
app:backgroundTint="#BEF60A0A"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.516"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.797" />
and in the kotlin file ( MainActivity.kt ), just add onClickListeners to the buttons inside the onCreate() as shown below:
class MainActivity : AppCompatActivity() {
lateinit var myBlueTooth : BluetoothAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myBlueTooth = BluetoothAdapter.getDefaultAdapter()
//Turn On Bluetooth
btnBluetoothOn.setOnClickListener {
if (myBlueTooth.isEnabled) {
//Show this toast if bluetooth is already ON
Toast.makeText(this, "BlueTooth is already ON", Toast.LENGTH_SHORT).show()
} else {
//Turn On bluetooth
var intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivity(intent)
}
}
btnBluetoothOff.setOnClickListener {
if (myBlueTooth.isEnabled) {
//Turn Off bluetooth
myBlueTooth.disable()
} else {
//Show this toast if bluetooth is already OFF
Toast.makeText(this, "BlueTooth is already Off", Toast.LENGTH_SHORT).show()
}
}
}
}
Add the below code in the AndroidManifest.xml for the permission
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Thanks for reading.