Android Question Permission denied to open Bluetooth device in Android 15

mario53

Member
Licensed User
Longtime User
Good morning, I have an application in B4A that enables BLUETOOTH, which I then use with a printer.
I've always worked perfectly with tablets running Android 14 and lower. Now I've changed tablets and am running Android 15. My application no longer works because it gives me this error:
java.lang.SecurityException: android.permission.BLUETOOTH_SCAN permission required for AttributionSource { uid = 10355, packageName = anysoftware.b4a.samples.bluetooth, attributionTag = null, token = android.os.BinderProxy@892f1fd, next = null }: starting detection.

I think I'm using the appropriate Manifest Editor
AddManifestText(
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="34"/>
<supports-screens android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
CreateResourceFromFile(Macro, Themes.LightTheme)
AddPermission(android.permission.ACCESS_FINE_LOCATION)
AddPermission(android.permission.BLUETOOTH_ADVERTISE)
AddPermission(android.permission.BLUETOOTH_CONNECT)
AddPermission(android.permission.BLUETOOTH_SCAN)
'End of default text.'

(Please note that my app will never be available on Google Play.)
Thanks in advance for any suggestions.
 

mario53

Member
Licensed User
Longtime User
bluetooth A14:
Dim PairedDevices As Map
    Dim deviceName, macAddress As String

    BtCon=False
    BtAdmin.Initialize("BlueTooth")
    BTConnection.Initialize("BTConnection")
    PairedDevices = BTConnection.GetPairedDevices
    Dim l As List
    'Dim deviceName, macAddress As String
    l.Initialize
    For i = 0 To PairedDevices.Size - 1 'Check all devices
        l.Add(PairedDevices.GetKeyAt(i))
        deviceName=PairedDevices.Getkeyat(i)
        macAddress=PairedDevices.GetValueAt(i)
        '"DC:0D:30:39:5A:4D"
        Log(deviceName & " -> " & macAddress)
        If macAddress="DC:0D:30:39:5A:4D" Then 'Insert the BT-Name of the printer or use the MAC address
            BTConnection.Connect(macAddress)
            BtCon=True
            Exit
        End If
    Next

the error line is
PairedDevices = BTConnection.GetPairedDevices
the error generated:
java.lang.SecurityException: Need android.permission.BLUETOOTH_CONNECT permission for AttributionSource { uid = 10355, packageName = anywheresoftware.b4a.samples.bluetooth, attributionTag = null, token = android.os.BinderProxy@669f87e, next = null }: AdapterService getBondedDevices

If I put in the manifest:
android:targetSdkVersion="32"
it gives the error
If I put:
android:targetSdkVersion="23"
not compatible with the phone
 
Upvote 0

LucasHeer

Active Member
Licensed User
Longtime User
Hey Mario!

As of SDK 31, you need to request permissions during runtime before interfacing Bluetooth. Are you doing this currently?:

B4X:
Dim Permissions As List
Dim phone As Phone
If phone.SdkVersion >= 31 Then
    Permissions = Array("android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH_CONNECT", rp.PERMISSION_ACCESS_FINE_LOCATION)
Else
    Permissions = Array(rp.PERMISSION_ACCESS_FINE_LOCATION)
End If
For Each per As String In Permissions
    rp.CheckAndRequest(per)
    Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then
        ToastMessageShow("No permission: " & Permission, True)
        Return
    End If
Next
 
Upvote 0

mario53

Member
Licensed User
Longtime User
yes ok now it gives me all the permissions but the bluetooth device found does not connect:
..:
       If macAddress="DC:0D:30:39:5A:4D" Then 'Insert the BT-Name of the printer or use the MAC address
            BTConnection.Connect(macAddress)
            Exit
        End If

education:
BTConnection.Connect(macAddress)
it doesn't give an error but it doesn't connect
 
Upvote 0

mario53

Member
Licensed User
Longtime User
After many tests and many studied examples, I would like to know if on Android 15 it is possible to print to an esc/pos printer with bluetooth
 
Upvote 0

LucasHeer

Active Member
Licensed User
Longtime User
yes ok now it gives me all the permissions but the bluetooth device found does not connect:
..:
       If macAddress="DC:0D:30:39:5A:4D" Then 'Insert the BT-Name of the printer or use the MAC address
            BTConnection.Connect(macAddress)
            Exit
        End If

education:
BTConnection.Connect(macAddress)
it doesn't give an error but it doesn't connect
Do you know for sure that it is calling BTConnection.Connect(macAddress)?

Maybe try this:
B4X:
        If macAddress="DC:0D:30:39:5A:4D" Then 'Insert the BT-Name of the printer or use the MAC address
            log("Connecting to printer...")
            BTConnection.Connect(macAddress)
            Exit
        End If

Also yes sir, it should 100% be possible on Android 15.

You may want to start here:
https://www.b4x.com/android/forum/threads/b4xpages-bluetooth-chat-example.119014/#content
 
Upvote 0

mario53

Member
Licensed User
Longtime User
I tried the example posted, adapting it to my needs, but I can't connect to the EscPos printer connected via Bluetooth.
The printer works perfectly with another app.

What am I doing wrong?

Thank you.
I'm attaching the example project.
 

Attachments

  • BluetoothChat.zip
    11 KB · Views: 86
Upvote 0

f0raster0

Well-Known Member
Licensed User
Longtime User
I tried the example posted, adapting it to my needs, but I can't connect to the EscPos printer connected via Bluetooth.
The printer works perfectly with another app.

What am I doing wrong?

Thank you.
I'm attaching the example project.
I tested your code and made a couple/quickly changes..
Probably someone can do it better :), but this version works for me on Android 16 (I only have 10, 11, 13, 14, and 16, no Android15) with my old mini Bluetooth thermal printer..

B4X:
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
Call B4XPages.GetManager.LogEvents = True to enable logging B4XPages events.
** Activity (main) Resume **
** Activity (main) Pause event (activity is not paused). **
** Activity (main) Resume **
test 1
test 2
** Activity (main) Pause event (activity is not paused). **
** Activity (main) Resume **
test 4
BlueTooth Printer -> 00:19:5D:25:E6:8D
Connecting to printer...
Printer OK!...
HELLO WORLD...


B4X:
'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=BluetoothChat.zip

Sub Class_Globals
    Private Root As B4XView 'ignore
    Private xui As XUI 'ignore

    Private btnSearchPermission As B4XView
    Private btnAllowConnection As Button
    Private btnPrint As Button

    Private rp As RuntimePermissions
    Private serial As Serial
    Type NameAndMac (Name As String, Mac As String)
    Private phone As Phone
    Dim astreams1 As AsyncStreams
    Dim PrintBuffer As String

    'Dim Version As Double = 2.0 ' Demo program version

End Sub

'You can add more parameters here.
Public Sub Initialize
 
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    'load the layout to Root
    Root.LoadLayout("1")
    serial.Initialize("serial")

End Sub

' Just to check if something strange is happening
Sub  astreams1_Error
    Log("astreams1 ERROR")
End Sub

Sub   astreams1_Terminated
    Log("astreams1 TERMINATED")
End Sub

Private Sub PermissionResult As ResumableSub
    Dim Permissions As List
    Dim phone As Phone
    If phone.SdkVersion >= 31 Then
        Permissions = Array("android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH_CONNECT", rp.PERMISSION_ACCESS_FINE_LOCATION)
    Else
        Permissions = Array(rp.PERMISSION_ACCESS_FINE_LOCATION)
    End If
 
    For Each per As String In Permissions
        rp.CheckAndRequest(per)
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
        If Result = False Then
            ToastMessageShow("No permission: " & Permission, True)
            Return False
        End If
    Next
    Log("PERMISSION'S - OK")

'    Return True
End Sub

Sub btnSearchPermission_Click
 
    Wait For(PermissionResult) Complete(res As Boolean)
    If res = False Then
        ToastMessageShow("not permission", False)
        ExitApplication
        Return
    End If
 
'    rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
'    Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'    If Result = False And rp.Check(rp.PERMISSION_ACCESS_COARSE_LOCATION) = False Then
'        'ToastMessageShow("No permission...", False)
'    
'        Log("test 1")
'        Return
'    End If
'    If phone.SdkVersion >= 31 Then
'        For Each Permission As String In Array("android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH_CONNECT")
'            rp.CheckAndRequest(Permission)
'            Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'            If Result = False Then
'                'ToastMessageShow("No permission...", False)
'            
'                Log("test 1")
'                Return
'            End If
'        Next
'    End If

 
End Sub

Sub btnAllowConnection_Click
    Log("test 1")
    If phone.SdkVersion >= 31 Then
        Log("test 2")
        rp.CheckAndRequest("android.permission.BLUETOOTH_CONNECT")
        Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
        If Result = False Then
            'ToastMessageShow("No permission...", False)
            Log("test 3")
            Return
        End If
    End If

    Log("test 4")
    Dim PairedDevices As Map
    PairedDevices = serial.GetPairedDevices
 
    Dim l As List
    Dim deviceName, macAddress As String
    l.Initialize
    For i = 0 To PairedDevices.Size - 1 'Check all devices
        l.Add(PairedDevices.GetKeyAt(i))
        deviceName=PairedDevices.Getkeyat(i)
        macAddress=PairedDevices.GetValueAt(i)
        '"DC:0D:30:39:5A:4D"
        Log(deviceName & " -> " & macAddress)
        If macAddress="00:19:5D:25:E6:8D" Then 'Insert the BT-Name of the printer or use the MAC address
            serial.Connect(macAddress)
            Log("Connecting to printer...")
            Sleep(500)
         
            Exit
        End If
    Next

End Sub

Sub btnPrint_Click
    '
    Dim cutting As String
    cutting = Chr(29) & "V" & Chr(66)
 
    Dim PrintBuffer As String
    PrintBuffer = Chr(27) & "t" & Chr(16)
    PrintBuffer = PrintBuffer & " HELLO WORLD" & CRLF ' Just change this text
    Log("HELLO WORLD...")
    astreams1.Write(PrintBuffer.GetBytes("UTF8"))
    astreams1.Write(cutting.GetBytes("UTF8"))
    astreams1.Write(Array As Byte(13, 10))

    astreams1.Close
 
    Return
End Sub

Sub serial_Connected (Success As Boolean)
    If Success Then
        astreams1.Initialize(Null,serial.OutputStream,"astreams1")
        'ToastMessageShow("Printer OK!",True)
        Log("Printer OK!...")
    Else
        'ToastMessageShow("Printer not found...",True)
        Log("Printer OK!...")
    End If
End Sub

Not sure if we need that (my manifest): AddPermission(android.permission.BLUETOOTH_ADVERTISE)
B4X:
'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
AddManifestText(
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="35"/>
<supports-screens android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
CreateResourceFromFile(Macro, Themes.LightTheme)
'End of default text.
AddPermission(android.permission.ACCESS_FINE_LOCATION)
'AddPermission(android.permission.BLUETOOTH_ADVERTISE)
AddPermission(android.permission.BLUETOOTH_CONNECT)
AddPermission(android.permission.BLUETOOTH_SCAN)

prrinter.jpg
 
Last edited:
Upvote 0

mario53

Member
Licensed User
Longtime User
Ho provato le tue modifiche e funzionano perfettamente su Android 14 e Android 16, ma non su Android 15.
Non capisco... Passerò ad Android 16.
Grazie @f0raster0
 
Upvote 0

mario53

Member
Licensed User
Longtime User
The program works well in Android 15, the problem was in the tablet, the printer was paired incorrectly, unfortunately this happens, thanks for the help
 
Upvote 0
Top