Process_Globals for a service

surfuric

Member
Licensed User
Longtime User
I have a service that is set to start at boot and runs every hour.

When the service finishes I issue a StartServiceAt("",NextRunTime,True) and then Service.StopForeground(1). I understand the service will start itself at the next specified run time even though it is no longer in the Foreground.

But my service depends on some Main.Process_Globals. So if within that hour the phone needed some resources and killed my Main (or I cold booted the phone), my Main.Process_Globals are uninitialized.

Specifically I have an HttpClient which needs to be initialized only once and I do so in Main. HttpClient does not seem to have an .isinitialized, so I can't tell if it is initialized later on or not.

I could lose my variables either by not running my service in the foreground, or by cold booting.

So, is it OK to re-initialize my httpclient each hour in the service just in case? I thought I read that this was not a good idea. I certainly do not want to keep my service in foreground, that seems bad form. Even worse, when starting from a cold boot, HTTPClient is not initialized at all.

Please let me know the best way to handle this.
Thanks!
 

surfuric

Member
Licensed User
Longtime User
But doesn't ispaused return true if the activity is not started yet, terminated, or paused. It simply means it is not active, but doesn't tell me if my HttpClient is initialized or not yet.

If it is paused, I should not re-initialize HttpClient. If it is not started or terminated I should, but what if it is simply sitting in the background.

Is it OK to execute another hc.Initialize("hc")? I was under the impression this was not a good idea.

Can you please elaborate?
 
Upvote 0

mc73

Well-Known Member
Licensed User
Longtime User
Not sure, but if process vars are lost, why should hc stay alive? Thus, you can simply hold a boolean flag set to true upon initialization and check its value when you run you service. If false, initialize the object. By the way, since you start your service at boot, why not initializing the http from there instead of the main activity? You can also set the flag there, so in case you need the object inside your main activity, you can know by its vaue if it's initialized or not.
 
Upvote 0

surfuric

Member
Licensed User
Longtime User
I looked through my code and realized why I did not initialize hc in the service. It is because it uses a class which is run by either Main or the Service. This class is the code which uses hc.

If main is up, it is not a problem (hc was initialized there and the class worked). But if the service was started without main being in the background, it caused a problem.

So, I will try the flag approach as suggested above. I was just hoping to check a little more elegantly. However, since hc does not have an isinitialized check, this may be the only way to figure it out.

Thanks everyone for your help.
 
Upvote 0
Top