Android Question When to use a Service

Markos

Active Member
Licensed User
Longtime User
Hi All

There are aspects of B4X I have not yet found a use as yet. The Service module. Can some explain when and why to use this feature. I can assume it isnto run methods or events as a background process. If that is the case Im wondering what are the benefits of using a usual module using timer events?
 

Markos

Active Member
Licensed User
Longtime User
Awesome.

So can we use a service for libraries as well or thats one exception where you must use an Activity.

I will look for examples on how to declare a service and the types of events and if to only use in the service module or can use in standard code modules or main.

I wont object to a quickie example link or pseudo code :)
 
Upvote 0

Markos

Active Member
Licensed User
Longtime User
Sorry
Awesome.

So can we use a service for libraries as well or thats one exception where you must use an Activity.

I will look for examples on how to declare a service and the types of events and if to only use in the service module or can use in standard code modules or main.

I wont object to a quickie example link or pseudo code :)
Ignore the parts about library that was invalid.

How to initialise and which modules are applicable will be helpful
 
Upvote 0

Markos

Active Member
Licensed User
Longtime User
Services are simpler than activities. Any code that is not related to the user interface can go in a service.

Service Modules
So if I put methods and subs in the service module but call them from anywhere it is more efficient processing where there is no interaction with gui objects?
So it is like a backgroud process thread ?

So lets say I put a timer in a code module and have the timer call subs defined in the service module. That is one practical use of the service module?
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User

First I started with ONE single Activity, too. It had several screens (via panels). As you can imagine, it was complicated to manage after a while.

Second try was to use several activities. So far so good. As I use a lot of databases I had to duplicate the code for each Activity. Almost 80% of the code was the same. Changing things lead to a change in ALL Activities. Very annoying. Today I use one or a few services for all that database stuff and one activity for every logical UI (like login, show items, change settings, etc.) Very easy to handle.
 
Upvote 0

Markos

Active Member
Licensed User
Longtime User
First I started with ONE single Activity, too. It had several screens (via panels). As you can imagine, it was complicated to manage after a while.

Second try was to use several activities. So far so good. As I use a lot of databases I had to duplicate the code for each Activity. Almost 80% of the code was the same. Changing things lead to a change in ALL Activities. Very annoying. Today I use one or a few services for all that database stuff and one activity for every logical UI (like login, show items, change settings, etc.) Very easy to handle.
Thanks for the real world reasoning. Now if I may ask your kind guidance. The activities and services are in essense different process threads that run in parallel to allow processes that can run independent of one another to do so to reduce processing anf tesponse tomes correct?

So while tgere are tutorials which I should read b4 asking I want to gast track my understandingbwhere posdible.

When you create 2 services will both be created under the starter module? And for a service to add value they are needed to run on their own steam checking and processing and producing output to say a file or data base when triggered by changes by say user interaction using an Activity thread.

Is this a fair and correct summary?

If u have a simple example u wish to share inproject form for Android and/or iOS thatd be most helpful!

Thanx
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
The activities and services are in essense different process threads that run in parallel to allow processes that can run independent of one another to do so to reduce processing anf tesponse tomes correct?

Only one Activity can run at a time. If you go to act2 then act1 will be paused. if you leave act2 then act1 will be resumed.
 
Upvote 0

FHEBERT

Member
Licensed User
Longtime User
Hello,
With Android Nougas, I meet a problem.

My service module restart every 5 seconds with this method:

#StartAtBoot: True
#StartCommandReturnValue: android.app.Service.START_STICKY

StartServiceAt(Me,DateTime.Now + (delay_synchro*DateTime.TicksPerSecond),True)

But when my phone is wakelocked, the service module is paused after 5 minutes.
If my phone is connected to charger, I have no problem.
I have deactivated the control of energy, But it does not change anything.

An idea ?
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
An idea ?
Why are you restarting a Sticky service?

What is the name of the service?
You should NOT Start/Stop/Restart the "Starter" service.
Do not set #StartAtBoot to true on the Starter-Service; Use another Service instead and set this service to StartAtBoot.

Probably it is the Energysaving-Feature of Doze which sends your app into sleep.
 
Upvote 0

FHEBERT

Member
Licensed User
Longtime User
The name of my service is "FTP_service"
This service connects to the FTP server every 5 seconds to check for an update

I use:

- sub Service_Create :
init FTP

- sub Service_Start :
FTP_download.List(Rep_serveur)

- sub FTP_ListCompleted
Function to list server Dir
.../
If return zéro then StopService(Me)
- sub FTP_DownloadCompleted
Function file download
.../
StopService(Me)
- sub Service_Destroy :
StartServiceAt(Me,DateTime.Now + (delay_synchro*DateTime.TicksPerSecond),True)


I must to create a service with #startAtboot = true for start the 'FTP_server" service ?
But how do I restart 'FTP_server" service 5 seconds later without stopservice ?
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
just use a timer that kicks in every 5 minutes and do your ftp calls there.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
The name of my service is "FTP_service"
This service connects to the FTP server every 5 seconds to check for an update
You are using a sticky service. Let the service running and just use a timer inside the service as suggested by @sorex
 
Upvote 0

FHEBERT

Member
Licensed User
Longtime User
Hello,
I have the same problem using a timer. (I let the service run)

After a few minutes, when the phone is idle, my timer stops.
If I activate my phone, the timer restarts
 
Upvote 0

FHEBERT

Member
Licensed User
Longtime User
Here my code.

B4X:
#Region Module Attributes
    #StartAtBoot: True
    #StartCommandReturnValue: android.app.Service.START_STICKY
#End Region

Sub Process_Globals
   
    Dim FTP_download As FTP
    Dim JobStatus As Int
    Dim STATUS_NONE, STATUS_WORKING, STATUS_DONE,STATUS_Destroy As Int
    Dim message As List
    STATUS_NONE = 0
    STATUS_WORKING = 1
    STATUS_DONE = 2
    STATUS_Destroy=3
   
    Public Rep_serveur_chat As String="/Chat/"
    Public DoneSuccessfully As Boolean=False
    Dim notif_mess As AdvancedNotification
    Dim num As Int=0
    Dim statut_main_up As Boolean=False
    Dim delay_synchro As Int=5
    Dim last_event As Long = DateTime.Now
    Dim file_downloaded As Int =0
    Dim timer_service As Timer
    Dim PI As PhoneId
    Dim read_data_param As String=""
    Dim Bconv As ByteConverter
    Dim Type_Param_init=4 As Int
    Dim FTP_adress As String=""
    Dim login As String=""
    Dim pwd As String=""
    Dim station As String=""
   
   
End Sub
Sub Service_Create

' Load init file
    initfile
   
   
   
    ' Initalisation du timer
   
    timer_service.Initialize("Timer_service",5000)
    timer_service.Enabled=True
   
   
    If FTP_download.IsInitialized=False Then
        FTP_download.Initialize("FTP", FTP_adress, 21, login, pwd)
    End If
   
    message.Initialize
    message.Clear
   
    notif_mess.Initialize
    notif_mess.Number=2
    notif_mess.Sound=False
   
End Sub

Sub Timer_service_Tick
   
    Try
        JobStatus=STATUS_WORKING
        FTP_download.List(Rep_serveur_chat)
    Catch
        ToastMessageShow("Erreur de lecture sur serveur FTP", True)
        Log(LastException)
    End Try
   
End Sub

Sub FTP_ListCompleted (ServerPath As String, Success As Boolean, Folders() As FTPEntry, Files() As FTPEntry)
 
  ' Relance une session FTP si déconnecté
    If Success=False Then
        'FTP_download.CloseNow
        FTP_download.CloseNow
        'StopService(Me)
        Log("defaut ftp : " & FTP_adress & "/" & login & "/" & pwd)
        FTP_download.Initialize("FTP", FTP_adress, 21, login, pwd)
    End If
   
   
        ' Charge les messages où je suis destinataire
    Try
        file_downloaded=0
         num =0
        For i = 0 To Files.Length - 1
       
            If Files(i).Name.Contains(station)=True Then
                num=num+1
                FTP_download.DownloadFile(Rep_serveur_chat & Files(i).Name, False,File.DirDefaultExternal, "/chat/" & "message" & num & ".log")
            End If
        Next
    Catch
        ToastMessageShow("Erreur de lecture sur serveur FTP", True)
        Log(LastException)
    End Try
   
    Log(num & " messages")
End Sub
 
Upvote 0

FHEBERT

Member
Licensed User
Longtime User
Why are you restarting a Sticky service?

What is the name of the service?
You should NOT Start/Stop/Restart the "Starter" service.
Do not set #StartAtBoot to true on the Starter-Service; Use another Service instead and set this service to StartAtBoot.

Probably it is the Energysaving-Feature of Doze which sends your app into sleep.

I think my problem is Doze.
Because, My phone behaves in the same way as other applications.

So i I have no solution..


Google extends the use of Doze, the service that puts the device into deep sleep when it is not used. Its field of action is broadened. With Marshmallow, it was activated shortly after the terminal is turned off and is flat, it is now activated as soon as the screen is turned off. For the record, it reduces most tasks in the background and synchronizes applications periodically, in a bundled way. What a dramatically increased standby time.
 
Upvote 0
Top