#Region Service Attributes
#StartAtBoot: False
#End Region
Sub Process_Globals
Private manager As BleManager2
Public connectedCentrals As Map
Private peripheral As BlePeripheral2
Public NotAvailable As Boolean
Private NativeMe As JavaObject
Private b() As Byte
End Sub
Sub Service_Create
NativeMe.InitializeContext
manager.Initialize("manager")
connectedCentrals.Initialize
End Sub
Sub Service_Start (StartingIntent As Intent)
Dim n As Notification
n.Initialize
n.Icon = "icon"
n.SetInfo("iBeacon Attivo", "Trasmissione in corso", Main)
Service.StartForeground(1, n)
StartAdvertising
End Sub
Sub Service_Destroy
StopAdvertising
Service.StopForeground(1)
End Sub
Private Sub StartAdvertising
Dim bc As ByteConverter
If manager.State=manager.STATE_POWERED_OFF Then
ToastMessageShow("Please enable Bluetooth", True)
NotAvailable = True
Else
peripheral.Initialize("peripheral", manager)
Dim bb As B4XBytesBuilder 'B4XCollections
bb.Initialize
bb.Append(Array As Byte(0x02, 0x15))
Dim bc As ByteConverter
bb.Append(bc.HexToBytes("0CF052C297CA407C84F8B62AAC4E9020"))
bb.Append(Array As Byte(0, 9, 0, 6, 0xb5))
b = bb.ToArray
peripheral.ManufacturerData = CreateMap(76: b )
Log(b.Length)
If peripheral.IsPeripheralSupported = False Then
ToastMessageShow("Peripheral mode not supported.", True)
NotAvailable = True
Else
Dim AdvertiseDataBuilder As JavaObject
AdvertiseDataBuilder = AdvertiseDataBuilder.InitializeNewInstance("android.bluetooth.le.AdvertiseData.Builder", Null)
If peripheral.ManufacturerData.IsInitialized Then
For Each key As Int In peripheral.ManufacturerData.Keys
Dim value() As Byte = peripheral.ManufacturerData.Get(key)
AdvertiseDataBuilder.RunMethod("addManufacturerData", Array(key, value))
Next
End If
Dim AdvertiseData As JavaObject = AdvertiseDataBuilder.RunMethod("build", Null)
Dim AdvertiseSettingsBuilder As JavaObject
AdvertiseSettingsBuilder = AdvertiseSettingsBuilder.InitializeNewInstance("android.bluetooth.le.AdvertiseSettings.Builder", Null)
AdvertiseSettingsBuilder.RunMethod("setConnectable", Array(False))
Dim callback As JavaObject
callback.InitializeNewInstance(Application.PackageName & ".foregroundbeacon$MyCallback", Null)
Dim jo As JavaObject = peripheral
jo.GetFieldJO("advertiser").RunMethod("startAdvertising", Array(AdvertiseSettingsBuilder.RunMethod("build", Null), _
AdvertiseData, Null, callback))
End If
End If
End Sub
Private Sub StopAdvertising
Dim callback As JavaObject
callback.InitializeNewInstance(Application.PackageName & ".foregroundbeacon$MyCallback", Null)
Dim jo As JavaObject = peripheral
jo.GetFieldJO("advertiser").RunMethod("stopAdvertising", Array(callback))
End Sub
#if Java
import android.bluetooth.le.*;
public static class MyCallback extends AdvertiseCallback {
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
BA.Log("Started successfully");
}
public void onStartFailure(int errorCode) {
BA.Log("failed to start: " + errorCode);
}
}
#End If