Android Question RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()

AbdurRahman

Member
Hi, first of all, much thanks for such super IDE
Its tiny, but no less than rocket in pocket

I migrated my signage system from kotlin to b4a
and development pace yet shoot up 🚀

I had challenge, to keep app running 24h
I'm using auto restart code (by @OliverA 😍)
with little help from gpt

B4X:
B4A=true
Group=UI
ModulesStructureVersion=1
Type=Service
Version=9.9
@EndOfDesignText@
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Private const FLAG_ACTIVITY_CLEAR_TOP As Int = 0x04000000
    Private const FLAG_ACTIVITY_CLEAR_TASK As Int = 0x00008000
    Private const FLAG_ACTIVITY_NEW_TASK As Int = 0x10000000
    Private const FLAG_ONE_SHOT As Int = 0x40000000
    Private const ALM_RTC As Int = 0x00000001
    Public AutoRestartEnabled As Boolean = True
    Public IsInForeground As Boolean = False
End Sub

Sub Service_Create
    EnsureNotificationChannel
    StartForegroundNotification
    StartServiceAt(Me, DateTime.Now + (5 * 1000), True)
    SaveMyLogs
End Sub

Sub Service_Start(StartingIntent As Intent)
    Log("Starter service started. Action=" & StartingIntent.Action)
    If StartingIntent.HasExtra("android.intent.extra.REASON") Or _
       StartingIntent.Action = "android.intent.action.BOOT_COMPLETED" Or _
       StartingIntent.Action = "android.intent.action.QUICKBOOT_POWERON" Or _
       StartingIntent.Action = "com.htc.intent.action.QUICKBOOT_POWERON" Then
        Log("Service restarted after boot")
    End If

    StartForegroundNotification

    If AutoRestartEnabled Then
        If IsPaused(Main) And IsPaused(PlayerWindow) And IsPaused(PasswordWindow) And IsPaused(DownWindow) Then
            Dim ctxt As JavaObject
            ctxt.InitializeContext
            Dim pm As JavaObject = ctxt.RunMethod("getPackageManager", Null)
            Dim launchIntent As Intent = pm.RunMethod("getLaunchIntentForPackage", Array(Application.PackageName))
            If launchIntent.IsInitialized Then
                launchIntent.Flags = Bit.Or(0x10000000, 0x20000000) ' NEW_TASK + CLEAR_TOP
                StartActivity(launchIntent)
            End If
        End If
        StartServiceAt(Me, DateTime.Now + (5 * 1000), True)
    End If
End Sub

Sub StartForegroundNotification
    If IsInForeground  Then Return
    Dim n As Notification
    n.Initialize
    n.Icon = "icon"
    n.AutoCancel = False
    n.SetInfo("App Running", "Monitoring…", Main)
    Service.StartForeground(1, n)
    IsInForeground = True
End Sub


Sub EnsureNotificationChannel
    Dim p As Phone
    If p.SdkVersion >= 26 Then
        Try
            Dim ctxt As JavaObject
            ctxt.InitializeContext
            Dim nm As JavaObject = ctxt.RunMethod("getSystemService", Array("notification"))
            Dim jc As JavaObject
            jc.InitializeNewInstance("android.app.NotificationChannel", Array("sig_channel_01", "Signal channel", 3))
            jc.RunMethod("setDescription", Array("Foreground service channel"))
            nm.RunMethod("createNotificationChannel", Array(jc))
        Catch
            Log("Notification channel creation failed: " & LastException.Message)
        End Try
    End If
End Sub


Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    SaveLog("Crash", Error.Message & CRLF & StackTrace)
    ScheduleRestartCrashedActivity(DateTime.Now + (2 * DateTime.TicksPerSecond), "Main", Error)
    ExitApplication
    Return True
End Sub

Sub ScheduleRestartCrashedActivity (Time As Long, ActivityName As String, message As String)
    Dim in As Intent
    in.Initialize("", "")
    in.SetComponent(Application.PackageName & "/." &  ActivityName.ToLowerCase)
    in.PutExtra("Crash", message)
    in.Flags = Bit.Or(FLAG_ACTIVITY_CLEAR_TASK, Bit.Or(FLAG_ACTIVITY_CLEAR_TOP, FLAG_ACTIVITY_NEW_TASK))
  
    Dim jin As JavaObject = in
    jin.RunMethod("setAction", Array(Null))
  
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim am As JavaObject = ctxt.RunMethod("getSystemService", Array("alarm"))
    Dim pi As JavaObject
    pi = pi.InitializeStatic("android.app.PendingIntent").RunMethod("getActivity", Array(ctxt, 0, in, FLAG_ONE_SHOT))
  
    Dim p As Phone
    If p.SdkVersion < 20 Then
        am.RunMethod("set", Array(ALM_RTC, Time, pi))
    Else If p.SdkVersion < 23 Then
        am.RunMethod("setExact", Array(ALM_RTC, Time, pi))
    Else
        am.RunMethod("setExactAndAllowWhileIdle", Array(ALM_RTC, Time, pi))
    End If
  
End Sub

Sub SaveLog(tag, text As String)
    Log($"ExtLOG(${tag},${text})"$)
    'Logger.addLogToDB2(tag, text)
End Sub
 
Sub ClearAdbLogs
    Try
        Dim jo As JavaObject
        jo.InitializeStatic("java.lang.Runtime")
        Dim runtime As JavaObject = jo.RunMethod("getRuntime", Null)
        runtime.RunMethod("exec", Array("logcat -c"))
        Log("Logcat cleared successfully")
    Catch
        Log("Error clearing logcat: " & LastException.Message)
    End Try
End Sub
 
Sub SaveMyLogs
    Try
        Dim jo As JavaObject
        jo.InitializeStatic("java.lang.Runtime")
        Dim runtime As JavaObject = jo.RunMethod("getRuntime", Null)
        Dim process As JavaObject
        process.InitializeStatic("java.lang.Runtime")
        Dim runtime As JavaObject = process.RunMethod("getRuntime", Null)
        Dim cmd As String = "logcat -d *:E"
        Dim proc As JavaObject = runtime.RunMethod("exec", Array(cmd))
        Dim br As JavaObject
        br.InitializeNewInstance("java.io.BufferedReader", Array( _
            br.InitializeNewInstance("java.io.InputStreamReader", Array(proc.RunMethod("getInputStream", Null))), _
            1024))
        Dim crashLogs As StringBuilder
        crashLogs.Initialize
        Do While True
            Dim line As String = br.RunMethod("readLine", Null)
            If line = Null Or line = "null" Then Exit
            crashLogs.Append(line).Append(CRLF)
            If crashLogs.Length > 5120 Then Exit
        Loop
        Dim base As String = File.DirRootExternal
        File.MakeDir(base, "Download")
        File.MakeDir(File.Combine(base, "Download"), "Signal")
        File.MakeDir(File.Combine(base, "Download/Signal"), "Logs")
        Dim filename As String = DateTime.Date(DateTime.Now) & "_" & DateTime.Time(DateTime.Now)
        filename = filename.Replace("/", "-").Replace(":", "-") & ".log"
        File.WriteString(File.Combine(base, "Download/Signal/Logs"), filename, crashLogs.ToString)
        ClearAdbLogs
    Catch
        Log("Error saving logs: " & LastException.Message)
    End Try
End Sub

My tester says same apk running fine on android 8
But close on android 11
Both are android boxes
B4X:
--------- beginning of main
--------- beginning of crash
09-30 14:16:17.473 29023 29023 E AndroidRuntime: FATAL EXCEPTION: main
09-30 14:16:17.473 29023 29023 E AndroidRuntime: Process: com.signal.android, PID: 29023
09-30 14:16:17.473 29023 29023 E AndroidRuntime: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{4a2abf8 u0 com.signal.android/.starter}
09-30 14:16:17.473 29023 29023 E AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2005)
09-30 14:16:17.473 29023 29023 E AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:106)
09-30 14:16:17.473 29023 29023 E AndroidRuntime:     at android.os.Looper.loop(Looper.java:223)
09-30 14:16:17.473 29023 29023 E AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:7664)
09-30 14:16:17.473 29023 29023 E AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
09-30 14:16:17.473 29023 29023 E AndroidRuntime:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
09-30 14:16:17.473 29023 29023 E AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
 

AbdurRahman

Member
Hi Erel, Thank you for posting that example
I tried, it did help, I copied some of tricks

But seems crash was occurred due to different issue.
Finally I identified it:

B4X:
11-07 02:40:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:40:45.751 I/chatty  (  674): uid=1000(system) CpuTracker expire 8 lines
11-07 02:40:56.060 I/chatty  (  674): uid=1000(system) Binder:674_5 expire 328 lines
11-07 02:41:00.003 I/chatty  (  674): uid=1000(system) ActivityManager expire 6 lines
11-07 02:41:04.654 I/chatty  (  674): uid=1000(system) android.bg expire 1 line
11-07 02:41:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:42:40.648 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:43:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:44:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:45:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:46:16.913 I/chatty  (  674): uid=1000(system) Binder:674_5 expire 342 lines
11-07 02:46:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:47:00.005 I/chatty  (  674): uid=1000(system) ActivityManager expire 17 lines
11-07 02:47:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:48:40.648 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:49:40.647 I/chatty  (    0): uid=0(root) logd identical 1 line
11-07 02:50:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:51:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:52:08.022 I/chatty  (  674): uid=1000(system) Binder:674_5 expire 660 lines
11-07 02:52:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:53:40.647 I/chatty  (    0): uid=0(root) logd identical 1 line
11-07 02:54:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:55:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:56:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:57:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:58:00.003 I/chatty  (  674): uid=1000(system) ActivityManager expire 6 lines
11-07 02:58:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 02:59:40.647 I/chatty  (    0): uid=0(root) logd identical 1 line
11-07 03:00:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 03:01:04.771 I/chatty  (  674): uid=1000(system) android.bg expire 5 lines
11-07 03:01:40.648 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 03:02:40.647 I/chatty  (    0): uid=0(root) logd identical 1 line
11-07 03:03:09.860 I/chatty  (  674): uid=1000(system) Binder:674_5 expire 140 lines
11-07 03:03:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au
11-07 03:04:00.002 I/chatty  (  674): uid=1000(system) ActivityManager expire 60 lines
11-07 03:04:40.647 W/healthd (    0): battery l=50 v=3 t=2.6 h=2 st=3 fc=100 chg=au

11-07 03:05:29.610 F/crashpad(27002): -----BEGIN CRASHPAD MINIDUMP-----
11-07 03:05:29.678 F/crashpad(27002): -----BEGIN CRASHPAD MINIDUMP-----
11-07 03:05:29.678 F/crashpad(27002): )iyJD'EEasi6<,451e#C,_aS9,cD8,}Mg...
11-07 03:05:29.742 F/crashpad(27002): -----END CRASHPAD MINIDUMP-----


11-07 03:05:30.229 F/libc    (12446): Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0xc0a25c0074000020 in tid 12446 (gnaladv.android), pid 12446 (gnaladv.android)
11-07 03:05:30.397 F/DEBUG   (27141): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
11-07 03:05:30.398 F/DEBUG   (27141): Build fingerprint: 'rockchip/rk3566_r/rk3566_r:11/RD2A.211001.002/zckj00907251755:userdebug/release-keys'
11-07 03:05:30.398 F/DEBUG   (27141): Revision: '0'
11-07 03:05:30.398 F/DEBUG   (27141): ABI: 'arm64'
11-07 03:05:30.399 F/DEBUG   (27141): Timestamp: 2025-11-07 03:05:30+0100
11-07 03:05:30.399 F/DEBUG   (27141): pid: 12446, tid: 12446, name: gnaladv.android  >>> com.signal.android <<<
11-07 03:05:30.399 F/DEBUG   (27141): uid: 10161
11-07 03:05:30.399 F/DEBUG   (27141): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0xc0a25c0074000020
11-07 03:05:30.399 F/DEBUG   (27141):     x0  00000074002e7fc0  x1  00000074002e7fc8  x2  0000007400fbcd30  x3  0000000000000010
11-07 03:05:30.399 F/DEBUG   (27141):     x4  0000007fda7dec38  x5  0000000000000001  x6  0000000029aaaaf1  x7  0000007c84174010
11-07 03:05:30.399 F/DEBUG   (27141):     x8  c0a25c0074000000  x9  00000074007acb40  x10 00000074007acb40  x11 0000000000000000
11-07 03:05:30.399 F/DEBUG   (27141):     x12 000000799671f9f0  x13 3836334535383239  x14 0000007400262968  x15 00000074001d0c00
11-07 03:05:30.399 F/DEBUG   (27141):     x16 0000000000000001  x17 0000007c813b9020  x18 0000007c83794000  x19 0000007400fbcd00
11-07 03:05:30.399 F/DEBUG   (27141):     x20 0000000000000000  x21 000000799671de80  x22 0000000000000001  x23 0000000000000000
11-07 03:05:30.399 F/DEBUG   (27141):     x24 00000076002d0170  x25 0000007996690a40  x26 0000000000000001  x27 00000076002d0208
11-07 03:05:30.399 F/DEBUG   (27141):     x28 00000076002d0018  x29 0000007fda7dec30
11-07 03:05:30.399 F/DEBUG   (27141):     lr  0000007991907d9c  sp  0000007fda7dec30  pc  0000007992c96df4  pst 0000000060001000
11-07 03:05:30.417 F/DEBUG   (27141): backtrace:
11-07 03:05:30.417 F/DEBUG   (27141):       #00 pc 000000000386cdf4  /data/app/~~btQ8kfbF0_4hL4Xni07kIw==/com.google.android.webview-GrY1Z9X3ozpAU_gC-Va00Q==/base.apk!libwebviewchromium.so (offset 0xe40000) (BuildId: 39fe1fcb1a536e4a9c66cd2349db3398f13e5b03)
11-07 03:05:30.417 F/DEBUG   (27141):       #01 pc 00000000024ddd98  /data/app/~~btQ8kfbF0_4hL4Xni07kIw==/com.google.android.webview-GrY1Z9X3ozpAU_gC-Va00Q==/base.apk!libwebviewchromium.so (offset 0xe40000) (BuildId: 39fe1fcb1a536e4a9c66cd2349db3398f13e5b03)
Seems native crash occur on webview, causing my app to crash also.
Is that possible to catch that ?
Secondly what webview version you recommend ? Currently we use 110.xx.

Note that our android boxes are rooted. So kiosk etc options possible, if you suggest any similar idea (to never let app close) ?
 
Upvote 0

AbdurRahman

Member
Use the latest possible. Try to find what might trigger this error. It is impossible to say based on the error message.
Strangely same app with same webview 110 works on android 11. But crash on 8.1 after running for few days.
GPT also suspect incompatibility, so i updated now to 141. Lets see.

Though also pasting minified code related to webview for review.
It works like: 1-5 containers(playlist) at same time on screen
Each container playing any of content: webview/video/image/pdf
Each content can run 5 to {custom} seconds, after moved to another content
and this signage keeps in loop.
B4X:
'container.bas
Sub Class_Globals
    Public Panel As Panel
    Public Box As Box
    Private Browser As WebView
    Private wve As WebViewExtras
    Private StopContainer As Boolean
    Private RootPanel As Panel
End Sub

Public Sub Initialize(Parent As Panel, C As Box, isTemplateLoad As Boolean)
    Try   
        Panel.Initialize("container")
        Panel.Color = Colors.Transparent
        Panel.Tag = Me
        Parent.AddView(Panel, C.X, C.Y, C.W, C.H)
        Browser.Initialize("Browser")
        Panel.AddView(Browser, 0, 0, Panel.Width, Panel.Height)
        RootPanel=Parent
        InitWeb
        Init(C, isTemplateLoad)
    Catch
        Loger.SaveEx(LastException)
    End Try
End Sub


Private Sub InitWeb
    Try
        If wve.IsInitialized = False Then wve.Initialize(Browser)
        Dim ws As WebSettings = wve.GetSettings
        wve.JavaScriptEnabled = True
        ws.SetDOMStorageEnabled(True)
        ws.SetLoadsImagesAutomatically(True)
        ws.SetAllowFileAccess(True)
        ws.SetJavaScriptCanOpenWindowsAutomatically(True)
        ws.SetUseWideViewPort(True)
        ws.SetLoadWithOverviewMode(True)

        Dim client As  DefaultWebViewClient
        client.Initialize("WebClient")
        wve.SetWebViewClient(client)
        Dim chrome As DefaultWebChromeClient
        chrome.Initialize("WebChrome")
        wve.SetWebChromeClient(chrome)
        ws.SetMediaPlaybackRequiresUserGesture(False)
        ws.setBuiltInZoomControls(True)
        ws.setSupportZoom(True)
    Catch
        Loger.SaveEx(LastException)
    End Try
End Sub

 
Private Sub ResizeChildren
    Try
        Browser.SetLayout( 0, 0, Panel.Width, Panel.Height)
    Catch
        Loger.SaveEx(LastException)
    End Try
End Sub

Public Sub Init(C As Box, isTemplateLoad As Boolean)
    Try
    Box = C
    If Box.contents <> Null And Box.contents.Size > 0 Then
        StopContainer = False
        Do While Not(StopContainer)
            For Each Content As Content In Box.contents
                Reset
                Select Case Content.mime.ToLowerCase
                    Case "url"
                        PlayUrl(Content.url)
                End Select
                If Content.duration > 0 Then
                    For i = 1 To Content.duration
                        If StopContainer Then Exit
                        Sleep(1000)
                    Next
                End If
            Next
        Loop
        End If
    Catch
        Loger.SaveEx(LastException)
    End Try
End Sub

Public Sub Dispose
    Try
        Reset
        Browser = Null
    Catch
        Loger.SaveEx(LastException)
    End Try
End Sub

Public Sub Reset
    Try
        If Browser.IsInitialized Then
            Try
                Browser.Visible = False
                wve.StopLoading
                wve.ClearCache(True)
                wve.ClearFormData
                wve.ClearHistory
                wve.ClearSslPreferences
                wve.LoadUrl("about:blank")
            Catch
                Loger.SaveEx(LastException)
            End Try           
        End If
    Catch
        Loger.SaveEx(LastException)
    End Try
End Sub

Private Sub PlayUrl(link As String)
    Try
        If Browser.IsInitialized Then
            Browser.LoadUrl("about:blank")
            Browser.LoadUrl(link)
            Browser.Visible = True
        End If
    Catch
        Loger.SaveEx(LastException)
    End Try
End Sub

1762778872355.png


Thanks for help ☺️
 
Upvote 0
Top