Untitled

mail@pastecode.io avatar
unknown
kotlin
7 months ago
2.1 kB
4
Indexable
Never
package com.example.btlo

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.app.Activity
import androidx.core.content.PermissionChecker

class MainActivity : AppCompatActivity() {
    private val REQUEST_ENABLE_BT = 1 // Any integer value

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Check if Bluetooth is supported on the device
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null) {
            // Device does not support Bluetooth
            // Handle this case as needed
            return
        }

        // Check if Bluetooth is already enabled
        if (!bluetoothAdapter.isEnabled) {
            // Bluetooth is not enabled, so request to enable it
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            try {
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
            } catch (e: Exception) {
                // Handle any exception that may occur (e.g., SecurityException)
                e.printStackTrace()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                // Bluetooth has been successfully enabled
                // You can perform Bluetooth-related operations here
            } else {
                // User declined to enable Bluetooth or an error occurred
                // Handle this case as needed
            }
        }
    }

}