After start my program, click the button, app falls. When I tried tutorials from other developers, Google, ... it doesnt solve the problem. I am ignoring startActivityForResult() is deprecated, I wanna ask user for turn on bluetooth - thats all.
The problem is on device with android 12.
Here are my permission from manifest file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Here is my code from MainActivity.kt
package com.example.piratsilnic
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val BTadapter = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
BTadapter.getAdapter()
var REQUEST_ENABLE_BT = 1
val sparovatButton = findViewById<Button>(R.id.sparovatButton)
sparovatButton.setOnClickListener{
if (BTadapter != null) {
if (BTadapter.adapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
if (BTadapter.adapter.isEnabled) {
Toast.makeText(this, "bluetooth on", Toast.LENGTH_LONG).show()
}
} else {
Toast.makeText(this, "Device doesnt support bluetooth", Toast.LENGTH_LONG).show()
}
}
}
}
I am lost little bit... thank you for help...
CodePudding user response:
You can use the newer registerForActivityResult()
To read more about it, there's a good guide on developers.android.com: Getting a result from an activity
First you would need to register your callback:
val registerForResult = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val intent = result.data
// Handle the Intent
}
}
Then, inside your onClickListener you would launch it.
if (BTadapter.adapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
regiterForResult.launch(enableBtIntent)
}