Android Tutorial [B4XPages] Bluetooth Chat Example

1592143666965.png


Updated implementation, based on B4XPages of https://www.b4x.com/android/forum/threads/android-bluetooth-bluetoothadmin-tutorial.14768/#content.

The code is much simpler compared to the previous example.
Note that you can call Serial.Listen without making the device discoverable. This is useful for cases where the devices were already paired once.

Updates:

- Example updated with targetSdkVersion 33. Note the new method to enable Bluetooth if needed.
- Example updated with targetSdkVersion 31 requirements.
Note the new permissions in the manifest editor:
B4X:
AddPermission(android.permission.ACCESS_FINE_LOCATION)
AddPermission(android.permission.BLUETOOTH_ADVERTISE)
AddPermission(android.permission.BLUETOOTH_CONNECT)
AddPermission(android.permission.BLUETOOTH_SCAN)
These are runtime permissions and are requested at runtime.

1687418029667.png
 

Attachments

  • BluetoothChat.zip
    18.2 KB · Views: 1,340
Last edited:

andredamen

Active Member
Licensed User
Longtime User
I have a problem with this example: It sticks with
Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
and don't get further in de program.

Bluetooth is on and the printer is detected in the tablet.

The first time I run the program it detected all the bluetooth devices. Later on it sticks with the wait for.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I have a problem with this example: It sticks with
Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
and don't get further in de program.

Bluetooth is on and the printer is detected in the tablet.

The first time I run the program it detected all the bluetooth devices. Later on it sticks with the wait for.
Are you using latest version of B4A?
 

GMan

Well-Known Member
Licensed User
Longtime User
The reason that I'm asking is that there was a bug in a previous version of RuntimePermissions that can cause it. I recommend you to delete all the internal libraries folder and reinstall B4A.
I an "old" app (SDK 26) Bluetooth works fine, but now in SDK 31 i got this message in the log:
B4X:
java.lang.SecurityException: Need android.permission.BLUETOOTH_SCAN permission for AttributionSource { uid = 10575, packageName = msgoethe.fpideenfabrik, attributionTag = null, token = android.os.BinderProxy@db75a4c, next = null }: Starting discovery.
I am using this in the manifest

B4X:
'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)
and this in the code:
B4X:
    rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)

When i try to set this:
B4X:
rp.CheckAndRequest(rp.PERMISSION_BLUETOOTH_SCAN)
it is red underlined and the description for this say:
B4X:
Unknown member permission_bluetooth_scan

What am i missing ?
B4A is up to date
 

GMan

Well-Known Member
Licensed User
Longtime User
Thx for the hint, but i could not figure it out.

Here is my code i used before:

B4X:
Sub btnSearchForDevices_Click
    rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
    'rp1.CheckAndRequest(rp1.PERMISSION_BLUETOOTH_SCAN)
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then
        ToastMessageShow("No permission...", False)
        Return
    End If
    Dim success As Boolean = Starter.Manager.SearchForDevices
    If success = False Then
        ToastMessageShow("Error starting discovery process.", True)
    Else
        ProgressDialogShow2("Suche nach MS Goethe...", False)
    End If
End Sub

Here is the new modul:

B4X:
Sub btnSearchForDevices_Click
    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)
        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)
                Return
            End If
        Next
    End If
    Dim success As Boolean = admin.StartDiscovery
    If success = False Then
        ToastMessageShow("Error starting discovery process.", True)
    Else
        CLV.Clear
        Dim Index As Int = ShowProgress
        Wait For Admin_DiscoveryFinished
        HideProgress(Index)
        If CLV.Size = 0 Then
            ToastMessageShow("No device found.", True)
        End If
    End If
End Sub

As i see, the new example is for B4XPages, i am using the "normal" code
 

GMan

Well-Known Member
Licensed User
Longtime User
I decided to make the whole enchilada new:
Spent more time for trying to re-configure the old app than it takes to make it new
 

red30

Well-Known Member
Licensed User
Longtime User
- Example updated with targetSdkVersion 33. Note the new method to enable Bluetooth if needed.

View attachment 143134
I tested this version on my Galaxy Tab A8 (Android 13). I get the error "Error starting discovery process.", even though I agree to all permission requests.
I realized that now using sdk 33, even for classic Bluetooth (not BLE), geolocation is now required. I don't know why this is happening, but now it is.
The same thing happens in the "[B4X] BLE 2 - Bluetooth Low Energy" library, if you do not enable geolocation, the device search process will not start...
 
Last edited:

Arf

Well-Known Member
Licensed User
Longtime User
I'm trying to incorporate the SDK 33 changes into my project, but getting something odd happening:
In my comms service's Service_Start I call the StartBluetooth function.
In that function (as per the example) the first thing the code does is check if admin.IsEnabled, which comes in at TRUE, so the resumable EnableBluetooth sub is not called and instead we advance on to try and listen, and the result of that is:
Units_Comms:StartListening failed as adaptor isn't ON
 

Arf

Well-Known Member
Licensed User
Longtime User
I am updating a large project that is many years old, it is not based on B4XPages.
 

Arf

Well-Known Member
Licensed User
Longtime User
So is the new method of enabling the Bluetooth adaptor specific to B4XPages, or is it needed with any project targeting SDK 33?
I have just doing some forum reading and see that services should not be used in 12+.. looks like I have a major rewrite of my project to do then.
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
or is it needed with any project targeting SDK 33?
Check this thread
 
  • Like
Reactions: Arf

Arf

Well-Known Member
Licensed User
Longtime User
With the new method of enabling BT adaptor, I don't understand the GetBA/ion part.

I have added the methods in the example to my project and now call StartBluetooth from an Activity, I see the toast message but then I get
java.lang.RuntimeException: Method: getBA not found in: com.mycompanyname.myappname.main

Do I need to change this line:
ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)

My project is not a B4X project.

if the getBA is specific to B4X, can I send a "android.bluetooth.adapter.action.REQUEST_ENABLE" intent with or without asking for user interaction? Intents ae a mystery to me so not sure how to do that anyway. Got about 3 hours to get an alpha test version of my app that just works on SDK onto the store so pretty desperate to turn this bluetooth adaptor on!

*****
NEVERMIND - I figured out a solution from HERE
 
Last edited:

Arf

Well-Known Member
Licensed User
Longtime User
The new method for enabling bluetooth adaptor is working for me, but I have a question.
In my prior project, I would ask the users permission to turn on Bluetooth if it is off (at app launch) and then when the user exits my app, I turn the bluetooth off again (only if it was off at app launch).

I presume that with SDK 33+ if I want to turn the bluetooth adaptor off again I will need to use a similar and request the user, but with a REQUEST_DISABLE intent?

Furthermore, since Bluetooth was off when my app was launched I would prefer to turn the Bluetooth off again without asking the user to simply leave it in the state it was in. Is that possible or not?
 
Top