Android Question Restart killed process/service

AHilberink

Active Member
Licensed User
Hi,

Manually move the process to trash, the service is also killed, but also the OS is killing it after longrun (deepsleepmode???)

I need to restart this service. Looking at processes like WhatsApp and Mail they seems to wakeup every time. I don't succeed in having a service running all the way.

My app is checking for messages from my server (and sending LatLon back every time).
I use the following code in a service not Starter:
B4X:
#Region  Service Attributes
    #StartAtBoot: True
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim Interval As Int:                Interval=2 'om de 2 minuten
    Dim n As Notification
    Private Check As Bitmap
    Dim lock As PhoneWakeState
End Sub

Sub Service_Create
    'This is the program entry point.
    'This is a good place to load resources that are not specific to a single activity.
    
    Check = LoadBitmapResize(File.DirAssets, "check.png", 24dip, 24dip, False)
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_WHEN_NEEDED
    lock.PartialLock
End Sub

Sub Service_Start (StartingIntent As Intent)
    Log("Done: "&DateTime.Time(DateTime.Now))
    OphalenMessages
    StartServiceAtExact(Me, DateTime.Now + Interval * DateTime.TicksPerMinute, True)
    Service.StopAutomaticForeground
End Sub

Sub Service_TaskRemoved
    'This event will be raised when the user removes the app from the recent apps list.
End Sub

'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub Service_Destroy
End Sub

Sub DisplayIcon (Body As String) As Notification
    Dim notif As NB6
    
    notif.Initialize("default", Application.LabelName, "HIGH").SmallIcon(Check)
    notif.SetDefaults(False,True,True)
    notif.AutoCancel(True)
    n.Initialize
    n=notif.Build("TEST", Body, "tag", Fingerprint)
    Return n
End Sub

Sub OphalenMessages
    << MY CODE >>
    if (newmessage=true) then
        Service.StartForeground(1,DisplayIcon("New message..."))
    End If
End Sub
Something like #StartCommandReturnValue: android.app.Service.START_STICKY is not supported anymore, but I need something simular, I think.

B4A v8.80 and Android 6.0 (and also 8.0.0)

I hope someone can help me making my service steady.

Best regards,
André
 

DonManfred

Expert
Licensed User

AHilberink

Active Member
Licensed User
no one of these are long running apps. They do not use any foregroundservices. Whatsapp get wake up by a Firebase Pushnotification.
https://www.b4x.com/android/forum/threads/automatic-foreground-mode.90546/
Example of a long running service: https://www.b4x.com/android/forum/threads/background-location-tracking.99873/
Thanks DonManfred,

I read as much as I clould find within the community and also these links. Thanks of course for your links.

Two difficulties:
- Automatic-foreground: I need it only when a message is available. Making it Always, I got a permanent Icon on my status bar. This Icon I only need on receive. Making it When needed or Never with a StartForeground, the process is killed (maybe because the interval of 2 like your second post?).
- Background-location: This example is based on a foreground notification every Service_Start. I made my service code likely the same (except the necessary notification every time I only need on receiving a message) as the example. A Application.Finish or moving to trash bin the service remains to be killed on Android 6.0. Android 8.0.0 is restarting the service after a while, but still killing it from time_to_time (mostly during the night, but I am still investigating).

Looking to the Active Services, processes like Mail and other Android basic processes are running from the start of my Phone and have no permanent Icon. Could it be done for my process also?
I read about Firebase pushnotifications, but I also need live tracking with the Activity closed and a background service still sending LatLon information to my server.

Change it to a minimum of 15 Minutes otherwise Android will kill your process (At least in newer Versions). Android does not allow you to restart a service in this interval.
Oeps, this interval is very big for sending LatLon tracking information to the office. To test steady process I will change it to 15, but do you have another suggestion to solve this?

Thanks for helping.

Best regards,
André
 

AHilberink

Active Member
Licensed User
Hi,

I read about this:
Android service run on UI thread so you should not execute long running task in it, like sending data to server. The approach you can use is ScheduledThreadPoolExecutor (preferred) or AlarmManager for scheduling and using asynctask or any other background thread for sending data to servers
Can someone point me to the right direction to build a long running task? I am not familiar with Java programming, just trying to build Android apps with the help of B4A.

Best regards,
André
 

AHilberink

Active Member
Licensed User
Hi,

Using the example MyLocation (1:1) as mentioned by DonManfred I have the same problem. MyLocation is killed and not restarted.

Reading over_and_over I find a big thinking error of myself. I thought "StartServiceAtExact" was the interval for the service. This is not correct, is it not?
I have to build my own timer within the service, because the service is already running (maybe helpfull for other beginners who think the same way).

I changed my code now:
B4X:
#Region  Service Attributes
    #StartAtBoot: True
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim Interval As Int:                Interval=2 'om de 2 minuten
    Dim n As Notification
    Private Check As Bitmap
    Dim lock As PhoneWakeState
    Dim CheckTimer As Timer
    Dim GPS1 As GPS
    Dim LatLon As String
    Dim Tracking As Boolean
End Sub

Sub Service_Create
    'This is the program entry point.
    'This is a good place to load resources that are not specific to a single activity.
   
    If(GPS1.IsInitialized=False) Then GPS1.Initialize("GPS")
    Check = LoadBitmapResize(File.DirAssets, "check.png", 24dip, 24dip, False)
    CheckTimer.Initialize("ItsTime", Interval*60000)  '1000 Milliseconds = 1 second
    Service.AutomaticForegroundMode=Service.AUTOMATIC_FOREGROUND_ALWAYS
    lock.PartialLock
End Sub

Sub Service_Start (StartingIntent As Intent)
    StartServiceAtExact(Me, DateTime.Now + 15 * DateTime.TicksPerMinute, True)
    If(CheckTimer.Enabled=False) Then CheckTimer.Enabled = True
    Track
End Sub

Sub Service_TaskRemoved
    'This event will be raised when the user removes the app from the recent apps list.
End Sub

'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub Service_Destroy
    Log("Destroyed")
    If Tracking Then
        GPS1.Stop
    End If
    Tracking = False
    lock.ReleasePartialLock
End Sub

Public Sub Track
    If Tracking Then Return
    If Starter.rp.Check(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION) = False Then
       Log("No permission")
       Return
    Else
       If(GPS1.GPSEnabled=True) Then
             GPS1.Start(20000,5)
       End If
    End If
    Tracking=True
End Sub

Sub ItsTime_Tick
    Log("Gedaan: "&DateTime.Time(DateTime.Now))
    If(EigenFuncties.Internet) Then OphalenMessages
End Sub

Sub DisplayIcon (Body As String) As Notification
    Dim notif As NB6
   
    notif.Initialize("default", Application.LabelName, "HIGH").SmallIcon(Check)
    notif.SetDefaults(False,True,True)
    notif.AutoCancel(True)
    n.Initialize
    n=notif.Build("TEST", Body, "tag", Fingerprint)
    Return n
End Sub

Sub OphalenMessages
    << MY CODE >>
    if (newmessage=true) then
        DisplayIcon("New message...")
    End If
End Sub

Sub GPS_LocationChanged (Location1 As Location)
    LatLon=Location1.Latitude&"/"&Location1.Longitude
End Sub
Now it is possible for me having a 2 minutes interval based on a timer within my service.

Are the following conclusions correct:
"#StartAtBoot: True" is only used to start my service after booting the device? (Working fine for me)
"StartServiceAtExact(Me, DateTime.Now + 15 * DateTime.TicksPerMinute, True)" is only a safety to restart the service after 15 minutes if killed/crashing?
A B4A Service is only a foreground service and will remain active as long as the application is loaded? As DonManfred mentioned "no one of these are long running apps. They do not use any foregroundservices. Whatsapp get wake up by a Firebase Pushnotification.". Using Firebase there should be also a longrunning listener to wake up Whatsapp or is it buildin OS? What kind of service is used?

Above service is working correctly on Android 6.0. It is killed on my killed Android 8.0.0, despite the instructions within https://www.b4x.com/android/forum/threads/automatic-foreground-mode.90546/.

It seems a difficult question. I hope someone can tell me what I am overlooking.

Best regards,
André
 

Erel

Administrator
Staff member
Licensed User
This is not correct, is it not?
No.

"#StartAtBoot: True" is only used to start my service after booting the device?
Yes.

"StartServiceAtExact(Me, DateTime.Now + 15 * DateTime.TicksPerMinute, True)" is only a safety to restart the service after 15 minutes if killed/crashing?
A B4A Service is only a foreground service and will remain active as long as the application is loaded?
The OS is not supposed to kill apps with foreground services (this is not always the case).

Using Firebase there should be also a longrunning listener to wake up Whatsapp or is it buildin OS? What kind of service is used?
Watch the push notifications video tutorial. It will be clear.
 
Top