Android Question [Solved] Foreground service and notifications

Roger C

Active Member
Licensed User
Longtime User
Hi all,

I have services that needs to be running all the time. Or rather wake up with StartServiceAt.

I used this code at first...
Code: Copy
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS

The problem is that it gives a notification sound/vibration every time I start the app.

So I tried this...
Code: Copy
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 
lock.PartialLock

' And in Service_Destroy:
lock.ReleasePartialLock
CancelScheduledService(Me)

This works. No sound or vibration at startup.
But is this a correct way to do it?
Will this service never be killed?



I know the forgroundservice in the first example must give a notificaton since it's Foreground and I don't mind the icon showing. I will use notifications myself in the app BUT I don't want the phone to vibrate and give a sound every time the app starts.
 
Thanks Erel!
Great support.

Edited:
***
But it still makes a Bing and vibrates when I start the app...
Isn't it possible to get rid of that?
***

So this code should work and the service will 'never' die? And it should be started at every 30 minutes?
With a visible notification in status bar?
Code: Copy
Sub Service_Create
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER
    lock.PartialLock
End Sub

Sub Service_Start (StartingIntent As Intent)
    Service.StartForeground(nid, CreateNotification("..."))
    StartServiceAt(Me, DateTime.Now + 30 * DateTime.TicksPerMinute, True)
End Sub

Sub Service_Destroy
    lock.ReleasePartialLock
    Service.StopAutomaticForeground
    CancelScheduledService(Me)
End Sub

Sub CreateNotification (Body As String) As Notification
    Dim notification As Notification
    notification.Initialize2(notification.IMPORTANCE_LOW)
    notification.Icon = "TrainClock36x36"
    notification.SetInfo("Tracking location", Body, Main)
    Return notification
End Sub
 
Last edited:
Upvote 0
So this code should work and the service will 'never' die? And it should be started at every 30 minutes?
Each thread should focus on a one specific question.

notification.Initialize2(notification.IMPORTANCE_LOW)
Notification with low importance shouldn't make any sound by default. Try to set Notification.Sound = False and Notification.Vibrate = False.
 
Upvote 0
But it still makes a Bing and vibrates when I start the app...
Isn't it possible to get rid of that?
B4X: Copy
Sub Service_Start (StartingIntent As Intent)
   Service.StartForeground(nid, CreateNotification("..."))
I tested that you can write:
B4X: Copy
Sub Service_Start (StartingIntent As Intent)
   Service.StartForeground(0, Null)
to avoid the first unwanted notification.

(however, I found "many" other problems ? :()
 
Upvote 0

Similar Threads

Back
Top