Android Tutorial Service Modules



Basic4android v1.2 adds support for Service modules.
Service modules play an important role in the application and process life cycle.
Start with this tutorial if you haven't read it before: Android Process and activities life cycle
Code written in an activity module is paused once the activity is not visible.
So by only using activities it is not possible to run any code while your application is not visible.
Services life cycle is (almost) not affected by the current visible activity. This allows you to run tasks in the background.
Services usually use the status bar notifications to interact with the user. Services do not have any other visible elements. Services also cannot show any dialog (except of toast messages).
Note that when an error occurs in a service code you will not see the "Do you want to continue?" dialog. Android's regular "Process has crashed" message will appear instead.

Before delving into the details I would like to say that using services is simpler than it may first sound. In fact for many tasks it is easier to work with a service instead of an activity as a service is not paused and resumed all the time and services are not recreated when the user rotates the screen. There is nothing special with code written in service.
Code in a service module runs in the same process and the same thread as all other code.

It is important to understand how Android chooses which process to kill when it is low on memory (a new process will later be created as needed).
A process can be in one of the three following states:
- Foreground - The user currently sees one of the process activities.
- Background - None of the activities of the process are visible, however there is a started service.
- Paused - There are no visible activities and no started services.

Paused processes are the first to be killed when needed. If there is still not enough memory, background processes will be killed.
Foreground processes will usually not be killed.

As you will soon see a service can also bring a process to the foreground.

Adding a service module is done by choosing Project - Add New Module - Service Module.
The template for new services is:
B4X:
Sub Process_Globals

End Sub

Sub Service_Create

End Sub

Sub Service_Start (StartingIntent As Intent)

End Sub

Sub Service_Destroy

End Sub
Sub Process_Globals is the place to declare the service global variables. There is no other Globals sub like in Activity as Service doesn't support Activity objects.
Sub process globals should only be used to declare variables. It should not run any other code as it might fail. This is true for other modules as well.
Note that Process_Global variables are kept as long as the process runs and are accessible from other modules.

Sub Service_Create is called when the service is first started. This is the place to initialize and set the process global variables. Once a service is started it stays alive until you call StopService or until the whole process is destroyed.
Sub Service_Start is called each time you call StartService (or StartServiceAt). When this subs runs the process is moved to the foreground state. Which means that the OS will not kill your process until this sub finishes running. If you want to run some code every couple of minutes / hours you should schedule the next task with StartServiceAt inside this sub.

Sub Service_Destroy is called when you call StopService. The service will not be running after this sub until you call StartService again (which will run Sub Service_Create followed by Sub Service_Start).
Service use cases

As I see it there are four main use cases for services.
- Separating UI code with "business" or logic code. Writing the non-UI code in a service is easier than implementing it inside an Activity module as the service is not paused and resumed and it is usually will not be recreated (like an Activity).
You can call StartService during Activity_Create and from now on work with the service module.
A good design is to make the activity fetch the required data from the service in Sub Activity_Resume. The activity can fetch data stored in a process global variable or it can call a service Sub with CallSub method.

- Running a long operation. For example downloading a large file from the internet. In this case you can call Service.StartForeground (from the service module). This will move your activity to the foreground state and will make sure that the OS doesn't kill it. Make sure to eventually call Service.StopForeground.

- Scheduling a repeating task. By calling StartServiceAt you can schedule your service to run at a specific time. You can call StartServiceAt in Sub Service_Start to schedule the next time and create a repeating task (for example a task that checks for updates every couple of minutes).

- Run a service after boot. By setting the #StartAtBoot attribute to True, our service will run after boot is completed.
Notifications

Status bar notifications can be displayed by activities and services.
Usually services use notifications to interact with the user. The notification displays an icon in the status bar. When the user pulls the status bar they see the notification message.

Example of a notification (using the default icon):

notification_1.png



notification_2.png


The user can press on the message, which will open an activity as configured by the Notification object.

The notification icon is an image file which you should manually put in the following folder: <project folder>\Object\res\drawable.
Accessing other modules

Process global objects are public and can be accessed from other modules.
Using CallSub method you can also call a sub in a different module.
It is however limited to non-paused modules. This means that one activity can never access a sub of a different activity as there could only be one running activity.
However an activity can access a running service and a service can access a running activity.
Note that if the target component is paused then an empty string returns.
No exception is thrown.
You can use IsPause to check if the target module is paused.

For example if a service has downloaded some new information it can call:
B4X:
CallSub(Main, "RefreshData")
If the Main activity is running it will fetch the data from the service process global variables and will update the display.
It is also possible to pass the new information to the activity sub. However it is better to keep the information as a process global variable. This allows the activity to call RefreshData whenever it want and fetch the information (as the activity might be paused when the new information arrived).

Note that it is not possible to use CallSub to access subs of a Code module.

Examples:
Downloading a file using a service module
Periodically checking Twitter feeds
 
Last edited:

LucaMs

Expert
Licensed User
I tested this code.

After closing the app (close button, ExitApplication) I can't see any process nor service in the "task manager".

I have not stopped the service, it should then restart the process, according to what was said in that post.
 

Attachments

  • lm ServiceTest.zip
    12.7 KB · Views: 390
Last edited:

Straker

Active Member
Licensed User
I tested this code.

After closing the app (close button, ExitApplication) I can't see any process nor service in the "task manager".

I have not stopped the service, it should then restart the process, according to what was said in that post.

You don't see services in taskmanager.
I cannot see your zip now. But probably your service has just ended and you don't have rescheduled it.

Therefore I think we're saying the same thing.
You say the closing the activity also the service dies, I'm saying that that the service is still running...
We have to test with a service that write the ticks in a file and see if the tick count increases also when the app is killed, or only when the service restart because scheduled.

Summary: does a service, with a long running task, continue to run after an activity.finish? And after an ExitApplication?
I say yes. The only way to programmatically stop a service is, I think, with ServiceStop.
HELP - Can someone answer the question?
 

LucaMs

Expert
Licensed User
Summary: does a service, with a long running task, continue to run after an activity.finish? And after an ExitApplication?
I say yes. The only way to programmatically stop a service is, I think, with ServiceStop.

Summary: does a service, with a long running task, continue to run after an activity.finish?

Activity.Finish closes the Activity, not the app (the process)!
You could start a service from within 3 of the 10 activities that compose your app or from a code module!

After ExitApplication: that post says that ExitApplication works only if you close any activity and stop any service and, if a service is not stopped, the process restarts. In that my test, I do not see the restart of the process.
 

Straker

Active Member
Licensed User
Ok, we have to check what happens to a service after ExitApplication. It's a good task for tomorrow...
 

Straker

Active Member
Licensed User
Summary:
A process is made by activities and services.
If the current activity is terminated with Activity?Finish, the service(s) is still alive.
If the app is terminated with ExitApplication also the services are terminated.
BUT if there is a scheduled service, this services will be created at the scheduled time.
...the 3rd proposition is to be checked...
 

Straker

Active Member
Licensed User
I tested this code.

After closing the app (close button, ExitApplication) I can't see any process nor service in the "task manager".

I have not stopped the service, it should then restart the process, according to what was said in that post.

You don't see the services. When 'task manager' is empty I have a couple of my services running (I know they are running because they beep every minute) and I think a lot of other services.

Probably you are perfectly right. ExitApplication kills also the service and if there is no scheduling, everything is dead.

Tomorrow I'll try to ExitApplication and see what happens to the service. Will it still beep or not? Who wants to bet?
 

DarkAngel

Member
Licensed User
Hi Erel,


I'm having an issue,


Suddenly my app stop calling a service, and when I use Callsub3(..) it returns:

“…

java.lang.NumberFormatException: Invalid double: "null"

…”

But it works with a backup that I have.

Could the project be corrupted or something is missing so the service it’s not starting.

I’m starting the service on activity create but it’s not starting the service… StartService(SEGUNDO_PLANO)
 

DarkAngel

Member
Licensed User
Here's the full error:
Copying updated assets files (3)


** Activity (main) Create, isFirst = true **


** Activity (main) Resume **


Error occurred on line: 586 (main)
java.lang.NumberFormatException: Invalid double: "null"


at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:269)
at java.lang.Double.parseDouble(Double.java:295)
at anywheresoftware.b4a.BA.ObjectToNumber(BA.java:622)
at com.roundsquarebox.radar.main._preenche_lista_alertas(main.java:2283)
at com.roundsquarebox.radar.main._update_screen(main.java:795)
at com.roundsquarebox.radar.main._activity_resume(main.java:1019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:636)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:305)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:238)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:121)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:171)
at com.roundsquarebox.radar.main.afterFirstLayout(main.java:106)
at com.roundsquarebox.radar.main.access$100(main.java:17)
at com.roundsquarebox.radar.main$WaitForLayout.run(main.java:78)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)

and the line 586 is: "If ((CallSub3(SEGUNDO_PLANO,"DEVOLVE_TEMPO",pnl_ALERTAS.Tag,"s")<=SEGUNDO_PLANO.int_REFRESH_RATE) AND (pnl_ALERTAS.Tag <>"")) OR Not(SEGUNDO_PLANO.bln_COMPRADO) Then Return"

Can't find a reason for this...that null makes no sense to me...
 

DarkAngel

Member
Licensed User
Hello Erel,

I just found what was causing the error...

I was calling the SERVICE before it was created, now it’s working fine.

:)
 

DarkAngel

Member
Licensed User
My service module is being stope when I make a memory clean. Since I use notifications, the notification stays alive and wont be removed until I restart the app again.
The Service_Destroy is not being called this way. Any way that I can remove the notification when the service is stop by the system?
 
Top