Android Bluetooth Permission not working on Android 13.
I want pop up for Permission to ask user for Bluetooth and location
Getting error in permission
package com.eapro.myproject
import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.content.*
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleGattCallback
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.callback.BleWriteCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.eapro.myproject.adapter.DeviceAdapter
class Connects : AppCompatActivity() {
Replace the UUID strings with the ones you have defined in your ESP32 code.
private val SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
private val CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8"
private val PIN = "12345"
Button ScanButton;
companion object {
private const val TAG = "Connect"
private val TAG: String = "Connect"
private const val REQUEST_CODE_OPEN_GPS = 1
private const val REQUEST_CODE_PERMISSION_LOCATION = 2
private const val REQUEST_CODE_PERMISSION_BLUETOOTH = 3
}
new changes for Android 12 and 13 are here
@RequiresApi(Build.VERSION_CODES.S)
private val PERMISSIONS_STORAGE = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_PRIVILEGED
)
@RequiresApi(Build.VERSION_CODES.S)
private val PERMISSIONS_LOCATION = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_PRIVILEGED
)
yaha se scanning part ho rhe hai list ke
private var mDeviceAdapter: DeviceAdapter? = null
private lateinit var mDeviceAdapter: DeviceAdapter
enko late initalisd krege hum
var progressBar: ProgressBar? = null
var bluetoothAdapter:BluetoothAdapter?=null
var recyclerView: RecyclerView? = null
var mList: MutableList<BleDevice>? = ArrayList()
var ScanningStopFlag = false
var view: View? = null
var connect: ConnectWithMac? = null
@RequiresApi(Build.VERSION_CODES.S)
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_connect)
view = window.decorView.findViewById(androidx.appcompat.R.id.content)
val view: View = window.decorView.findViewById(android.R.id.content)
//ScanButton = findViewById(R.id.startScan);
progressBar = findViewById(R.id.progressBarScan)
recyclerView = findViewById(R.id.deviceRecyclerView)
mList = mutableListOf() //ArratList()
mDeviceAdapter = DeviceAdapter(this, mList)
bluetoothAdapter=BluetoothAdapter.getDefaultAdapter()
Log.d("","myadapter"+bluetoothAdapter)
recyclerView?.setLayoutManager(
LinearLayoutManager(
this, LinearLayoutManager.VERTICAL,
false
)
)
recyclerView?.setAdapter(mDeviceAdapter)
checkPermissions() //To check location permission
BleManager.getInstance().init(application)
BleManager.getInstance()
.enableLog(true)
.setReConnectCount(1, 5000)
.setSplitWriteNum(5)
.setConnectOverTime(100).operateTimeout = 600
connect = ConnectWithMac(
applicationContext,
view, R.id.progressBarScan, false
)
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_CODE_PERMISSION_BLUETOOTH);
}
if (!mac.equals("0")) {
connectWithMAC(mac);
//
}
else {
ScanButton.setVisibility(View.VISIBLE);
scanDevice();
// }
}
error
override fun onStart() {
super.onStart()
ScanningStopFlag = true
error
callScanning()
mDeviceAdapter?.notifyDataSetChanged()
}
override fun onStart() { // in kotlin we have this code
super.onStart()
ScanningStopFlag = true
callScanning()
mDeviceAdapter.notifyDataSetChanged()
}
override fun onStop() {
super.onStop()
connect?.stopConnecting()
ScanningStopFlag = false // yaha ban skta hai scenerio
cancelScanning()
}
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
super.onBackPressed()
connect?.stopConnecting()
ScanningStopFlag = false // yaha bhi ban skta hai scenerio
cancelScanning()
showscanlist()
}
private fun showscanlist() {
TODO("Not yet implemented")
}
override fun onRestart() {
super.onRestart()
callScanning()
ScanningStopFlag = true
}
//error
@SuppressLint("MissingPermission")
fun callScanning() {
val mac: String = mDeviceAdapter!!.mac
if (isBluetoothEnabled) {
if (mac != "0") {
Log.d(TAG, "MAC")
//TODO: implement this in project / https://github.com/jlmd/AnimatedCircleLoadingView
connect?.connectWithMAC(mac)
connect?.setListener { bleDevice ->
val intent = Intent(this@Connects, MainScreen::class.java)
intent.putExtra("bleDevice", bleDevice)
finish()
startActivity(intent)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
}
else {
ScanButton.setVisibility(View.VISIBLE);
scanDevice()
}
else {
bluetoothAdapter?.enable()
callScanning()
}
}
@SuppressLint("MissingPermission")
fun scanDevice() {
if (isBluetoothEnabled) {
BleManager.getInstance().scan(object : BleScanCallback() {
override fun onScanStarted(success: Boolean) {
progressBar!!.visibility = View.VISIBLE
println("scanning")
}
override fun onScanning(bleDevice: BleDevice) {
if (!mList!!.contains(bleDevice)) {
Log.d(TAG, bleDevice.mac) // ble list ko log krege yaha pr
mList!!.add(bleDevice)
mDeviceAdapter?.notifyDataSetChanged()
}
}
override fun onScanFinished(scanResultList: List<BleDevice>) {
Log.d(TAG, "Scanning finished")
progressBar!!.visibility = View.INVISIBLE
if (ScanningStopFlag) {
Handler().postDelayed({ //Do something after 100ms
mList!!.clear()
scanDevice()
8000)
}
}
})
else {
bluetoothAdapter!!.enable()
scanDevice()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE_PERMISSION_LOCATION) {
if (grantResults.isNotEmpty()) {
for (i in grantResults.indices) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted(permissions[i])
}
}
}
}
}
@RequiresApi(Build.VERSION_CODES.S)
private fun checkPermissions() {
val permission1 =
ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
val permission2 = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN)
if (permission1 != PackageManager.PERMISSION_GRANTED) {
We don't have permission so prompt the user
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
1
)
else if (permission2 != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_LOCATION,
1
)
}
}
private fun onPermissionGranted(permission: String) {
when (permission) {
Manifest.permission.ACCESS_FINE_LOCATION -if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !checkGPSIsOpen()) {
AlertDialog.Builder(this)
.setTitle(R.string.notifyTitle) // services hai
.setMessage(R.string.gpsNotifyMsg)
.setNegativeButton(R.string.cancel,
DialogInterface.OnClickListener { dialog, which -finish() })
.setPositiveButton(R.string.setting,
DialogInterface.OnClickListener { dialog, which ->
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivityForResult(intent, REQUEST_CODE_OPEN_GPS)
})
.setCancelable(false)
.show()
}
Manifest.permission.BLUETOOTH_CONNECT -if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !isBluetoothEnabled) {
AlertDialog.Builder(this)
.setTitle(R.string.notifyTitle)
.setMessage(R.string.bleNotifyMsg)
.setNegativeButton(R.string.cancel,
DialogInterface.OnClickListener { dialog, which -finish() })
.setPositiveButton(R.string.setting,
DialogInterface.OnClickListener { dialog, which -openBluethooth() })
.setCancelable(false)
.show()
}
Manifest.permission.BLUETOOTH_CONNECT -if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !isBluetoothEnabled) {
AlertDialog.Builder(this)
// .setTitle(R.string.notifyTitle)
// .setMessage(R.string.bleNotifyMsg)
// .setNegativeButton(R.string.cancel,
DialogInterface.OnClickListener { dialog, which -finish() })
// .setPositiveButton(R.string.setting,
DialogInterface.OnClickListener { dialog, which -openBluethooth() })
// .setCancelable(false)
// .show()
// }
}
}
@SuppressLint("MissingPermission")
private fun openBluethooth() {
val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(intent, REQUEST_CODE_PERMISSION_BLUETOOTH)
}
private fun openBluetooth() {
val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(intent, REQUEST_CODE_PERMISSION_BLUETOOTH)
in kotlin we have this code
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_OPEN_GPS) {
if (checkGPSIsOpen() && isBluetoothEnabled) {
callScanning()
}
else if (requestCode == REQUEST_CODE_PERMISSION_BLUETOOTH) {
if (checkGPSIsOpen() && isBluetoothEnabled) {
callScanning()
}
}
}
Function to initiate pairing with the selected BLE device
fun initiatePairing(bleDevice: BleDevice) {
BleManager.getInstance().disconnectAllDevice()
BleManager.getInstance().disconnect(bleDevice)
BleManager.getInstance().connect(bleDevice, object : BleGattCallback() {
override fun onStartConnect() {
Called when the connection starts
// }
//
override fun onConnectFail(bleDevice: BleDevice?, exception: BleException?) {
Called when the connection fails
// }
//
override fun onConnectSuccess(bleDevice: BleDevice?, gatt: BluetoothGatt?, status: Int) {
Called when the connection is successful
Initiate pairing
pairWithDevice(bleDevice)
// }
//
override fun onDisConnected(isActiveDisConnected: Boolean, device: BleDevice?, gatt: BluetoothGatt?, status: Int) {
Log.d(TAG, bleDevice.mac)
Called when the device is disconnected
// }
// })
// }
Function to pair with the BLE device
private fun checkGPSIsOpen(): Boolean {
val locationManager = this.getSystemService(LOCATION_SERVICE) as LocationManager
return false
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}
private val isBluetoothEnabled: Boolean
get() = bluetoothAdapter!!.isEnabled
fun cancelScanning() {
if (ScanningStopFlag) {
BleManager.getInstance().cancelScan()
}
}
}
here is an error I am getting.
FATAL EXCEPTION: main
Process: com.eapro.myproject, PID: 960
java.lang.SecurityException: Need android.permission.BLUETOOTH_CONNECT permission for AttributionSource { uid = 10179, packageName = com.eapro.myproject, attributionTag = null, token = android.os.BinderProxy@708e21f, next = null }: enable
android.os.Parcel.createExceptionOrNull(Parcel.java:3023)
android.os.Parcel.createException(Parcel.java:3007)
android.os.Parcel.readException(Parcel.java:2990)
android.os.Parcel.readException(Parcel.java:2932)
android.bluetooth.IBluetoothManager$Stub$Proxy.enable(IBluetoothManager.java:724)
android.bluetooth.BluetoothAdapter.enable(BluetoothAdapter.java:2436)
New contributor
Android test is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4