Android Question Use of Timers

Harris

Expert
Licensed User
After going thru my code and cleaning up (massive) warnings of un-used vars.

I don't understand why timers should be declared in process globals (warning 13)?

I use timers everywhere in activities and service mods... I usually call them the same name...
I pause (disable) and resume them in activities as required. They seem to work fine in this manner.
 

Erel

Administrator
Staff member
Licensed User
The first question is why not? Generally speaking all non-UI objects should be declared in Process_Globals.

If you are careful and always pause the timers in Activity_Pause then it will work fine. The problems start when you don't pause the timer. Now whenever the orientation changes (for example) a new timer will be created.
 

thedesolatesoul

Expert
Licensed User
What you are saying makes complete sense to me, but I dont understand how it works.
When the activity dies, the message queue doesnt, so the timers in globals stay alive/cannot be GC. The timers in Process_Globals will have their references intact.

So are you saying even after the timer message has been posted (and handled), the message queue still holds a reference to the timer?
How does this happen, isnt the message queue just a handler?
 

Erel

Administrator
Staff member
Licensed User
If the timer is enabled then it will not be GC. The problem with global timers is that later when the activity is recreated a new timer will be created.
You can easily find yourself with multiple timers ticking instead of a single one.

If the timer is a process global then a new timer will not be created when the activity is created.

So are you saying even after the timer message has been posted (and handled), the message queue still holds a reference to the timer?
If the timer is not paused then it will post a new message each time that it ticks.
 

Harris

Expert
Licensed User
B4X:
Sub Activity_Pause (UserClosed As Boolean)

    If UserClosed Then
       Awake.ReleasePartialLock
    End If 
    Tim1.Enabled = False

End Sub

Sub Activity_Resume
    If Tim1.IsInitialized = False Then
       Tim1.Initialize("Tim1",  timint)
       Tim1.Enabled = True
    Else
       If Tim1.Enabled = False Then
          Tim1.Interval = timint
          Tim1.Enabled = True
          UPDbutton
       End If
    End If
End Sub
This is with timer in Globals... It works well enough but I certainly want to avoid all dangers...

Good advice.. I shall clean up and put non-UI in process_globals

Thanks all.
 

Erel

Administrator
Staff member
Licensed User
So what I am trying to understand that when a Timer is a Global variable, why doesnt it get GC'd when the Activity is killed. What is holding a reference to this timer, and how, and why?
It will be released if you properly disable it when the activity is paused. Otherwise you will have a "timer leak".
 
Top