Android Question [solved] Error/Crash : Start scheduling after rebooting the smartphone

voxel

Active Member
Licensed User
Hi,
I've coded a foreground service. It works fine with StartServiceAt with notification (wake-up once a day).
The problem is starting it after a smartphone reboot.
I get this error:

java.lang.RuntimeException: android.app.ForegroundServiceStartNotAllowedException: FGS type dataSync not allowed to start from BOOT_COMPLETED!

So I have in the Create of the service :

B4X:
#Region  Service Attributes
    #StartAtBoot: True
 
#End Region


Sub Service_Create
 
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER

End Sub


Sub Service_Start (StartingIntent As Intent)

    Log("Service démarré")
 
    If StartingIntent.IsInitialized And StartingIntent.Action = "android.intent.action.BOOT_COMPLETED" Then

        Dim n As Notification
        n.Initialize
        n.Icon = "icon_notif"
        n.AutoCancel = True
        n.SetInfo2("Lyzo","Analyse","",Main)
        n.Notify(1)
        Service.StartForeground(1,n)
 
        ScheduleNextDownload

        Service.StopAutomaticForeground


I now have this error on Service_Destroy (and crash) :

B4X:
--------- beginning of main
** Receiver (servicenotification) OnReceive **
*** Service (starter) Create ***
** Service (starter) Start **
** Service (servicenotification) Create **
Service crée
** Service (servicenotification) Start **
Service started in foreground mode.
Service démarré
Redémarrage détecté : on planifie ServiceNotification
Initialise StartServiceAt
Prochain téléchargement planifié pour : 08/18/2025-12:00:00
** Service (servicenotification) Destroy **
Service arrêté
android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{b2d92c2 u0 fr.lyzo/.servicenotification c:fr.lyzo}
    at android.app.ActivityThread.generateForegroundServiceDidNotStartInTimeException(ActivityThread.java:2313)
    at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:2281)
    at android.app.ActivityThread.-$$Nest$mthrowRemoteServiceException(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2599)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loopOnce(Looper.java:232)
    at android.os.Looper.loop(Looper.java:317)
    at android.app.ActivityThread.main(ActivityThread.java:8756)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:601)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:962)

I'm not sure I'm on the right track, thank you for your help.
I just want my once-daily scheduling service to work when I restart my phone.



Manifest :

B4X:
SetServiceAttribute(ServiceNotification, android:foregroundServiceType, dataSync)
AddPermission(android.permission.POST_NOTIFICATIONS)
AddPermission(android.permission.FOREGROUND_SERVICE)
AddPermission(android.permission.RECEIVE_BOOT_COMPLETED)
 
Last edited:

voxel

Active Member
Licensed User
Thank you.
I just tried the Receiver using this code: https://www.b4x.com/android/forum/threads/background-location-tracking.99873/
But I have the same problem when the service stops.
I'm lost, I don't understand how to do it.
Can I still use a service to schedule once a day using StartServiceAt?

ReceiverNotification:
Sub Process_Globals
   
End Sub

Private Sub Receiver_Receive (FirstTime As Boolean, StartingIntent As Intent)
   
    StartForegroundService(ServiceNotification)
   
End Sub


Private Sub StartForegroundService(Service As Object)
    Dim p As Phone
    If p.SdkVersion <= 26 Then
        StartService(Service)
        Return
    End If
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim intent As JavaObject
    intent.InitializeNewInstance("android.content.Intent", Array(ctxt, Service))
    ctxt.RunMethod("startForegroundService", Array(intent))
End Sub


ServiceNotification:
#Region  Service Attributes
    #StartAtBoot: False
   
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Service_Create
   
    Log("Service crée")
   
End Sub

Sub Service_Start (StartingIntent As Intent)

    Log("Service démarré")


Log:
--------- beginning of main
*** Receiver (receivernotification) Receive (first time) ***
*** Service (starter) Create ***
** Service (starter) Start **
** Service (servicenotification) Create **
Service crée
** Service (servicenotification) Start **
Service démarré
Base de données OK : Version : 53
*** Receiver (httputils2service) Receive (first time) ***
Téléchargement OK : Version : 53
Lancement notification
Pas de nouvelle analyse
Initialise StartServiceAt
Prochain téléchargement planifié pour : 08/19/2025-12:00:00
** Service (servicenotification) Destroy **
Service arrêté
android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{b6e9a9f u0 fr.lyzo/.servicenotification c:fr.lyzo}


Manifest:
SetServiceAttribute(ServiceNotification, android:foregroundServiceType, shortService)
AddPermission(android.permission.POST_NOTIFICATIONS)
AddPermission(android.permission.FOREGROUND_SERVICE)
AddPermission(android.permission.RECEIVE_BOOT_COMPLETED)
AddReceiverText(ReceiverNotification, <intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>)
 
Last edited:
Upvote 0

voxel

Active Member
Licensed User
If I change ReceiverNotification to only StartService, I no longer have any problems. Is this the right method?

ReceiverNotification:
Sub Process_Globals
    
End Sub

Private Sub Receiver_Receive (FirstTime As Boolean, StartingIntent As Intent)
    
    StartService(ServiceNotification)
    
End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
1. Make sure to handle the Timeout event, as required with shortService service type:
B4X:
Private Sub Service_Timeout(Params As Map)
    Service.StopForeground(NotificationId)
End Sub

2.
If I change ReceiverNotification to only StartService, I no longer have any problems. Is this the right method?
Assuming that the service is really needed then it is a valid solution.
 
Upvote 0

voxel

Active Member
Licensed User
My need is to perform a download once a day (around 12pm) (processing is very fast) and display a notification. Is there another way than using a Service? Can I use only a Receiver?
 
Last edited:
Upvote 0

voxel

Active Member
Licensed User
I just replaced Service with Receiver. When I restart the smartphone, it works fine, the notification appears.
But when I program for the next alarm with StartReceiverAt, it doesn't wake up the next day.


B4X:
    Dim now As Long = DateTime.Now

    Dim today As String = DateTime.Date(now)

    Dim target As Long = DateTime.DateTimeParse(today, "12:00:00")

    If target < now Then target = target + DateTime.TicksPerDay

 
    StartReceiverAt(Me, target, False)

    Log("Prochain téléchargement planifié pour : " & DateTime.Date(target) & "-" & DateTime.Time(target))



But with this code, the alarm works fine

B4X:
StartReceiverAt(Me, DateTime.Now + DateTime.TicksPerMinute * 3, False)
 
Last edited:
Upvote 0

voxel

Active Member
Licensed User
I just found the problem: when the smartphone is in sleep mode, the receiver doesn't start.
Even if I set "During Sleeping" to True, I have the same problem.
Any ideas?

B4X:
StartReceiverAt(Me, DateTime.Now + DateTime.TicksPerMinute * 3, True)
 
Upvote 0

voxel

Active Member
Licensed User
Android does not allow you to start it in such a small interval. Set it to 30+ Minutes or a hour.
It took me 3 minutes to test, and the StartReceiverAt wakes up fine when the smartphone isn't in sleep/lock mode.
I ran a test by turning it on once a day, and I got nothing.
I'm wondering if there's a battery optimization that's pausing the Receiver? Because when I wake up the smartphone, the Receiver starts working again.

I just tried again every 30 minutes, same problem :-(


Update :

With a
- Samsung Galaxy A13 / Android 14: alarm OK every 30 minutes
- Xiaomi Redmi A3 / Android 15: alarm KO

I have the impression that the Receiver's behavior is erratic. Is this a restriction on Android 15?

I will open a new Thread.
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…