Android Example Foreground Service with Notification Builder

The app I'm building will allow the user to configure a series of timed actions, then execute them in order using "play" controls looking much like a music player (play/pause, skip forward/backward etc.)

I wanted a way for the execution to continue even if the app wasn't in the foreground, and for the user to be able to access key controls even when the app was "hidden" so I explored the option of using a foreground service with a notification for the user to control/return to the app if the app was no longer in the foreground.

The attached example uses information and examples from the following posts:
* Downloading files using Service module: https://www.b4x.com/android/forum/threads/downloading-files-using-service-module.7572
* Notification Builder Library: https://www.b4x.com/android/forum/threads/notification-builder-library.27376/

The example shows how to implement a long-running service (Service.StartForeground) with three different ways to show a notification used for controlling the app:
1) Using the Notification object and catching the user press on the notification (based on Erel's download example)
2) Using the NotificationBuilder library (see above for link to the library) and catching the user press on the notification
3) Using the NotificationBuilder library with additional actions to implement the controls

Note that all three examples raise the user action in the main activity. In the final app, these actions will be raised in the UI activity that displays and controls the playback. This activity will "wrap" the service that is executing the timed actions / playing sounds as appropriate.

I initially struggled with how to code items (2) and (3), so took the step by step approach. I plan to use additional Notification Builder capabilities in the final app (and will be making a contribution to barx), but with the groundwork already done, the additional capabilities should be easier to implement.

Enjoy!
 

Attachments

  • LongRunningService.zip
    11.6 KB · Views: 803
Last edited:

davidvidasoft

Member
Licensed User
Hi @Misterbates, I was trying out the example but I am encountering some errors because I am using B4A V8.0. Looks like I need to move some lines before the SetInfo method, also I need to reinitialize the notification object every time I want to change its properties (the error is very literal) but I don't know if it's appropiate to do it just before using SetInfo(...) because now the notification disappears from the drawer. How would you do it? I'm trying to fix the example but no success :/

EDIT: The error about reinitializing the notification object only happens with the Normal Notification button. The other two buttons work as expected.
 
Last edited:
Top