'Main Loop in Android Activity

Where can I find the main loop in android or how can I implement it?
If I for example want to increment x every time it runs through the activity and test if x exceeds a value, how would I do that when there is no main loop?



Solution 1:[1]

The main thread runs a Looper, which is an event-dispatcher (probably what you are referring to as "main loop"). The Looper is responsible to dispatching events and running small chunks of code. You can't get into the Looper on every pass, but you can post small chunks of code to the Looper to get executed, and you can schedule code to be run at a certain time. To do this, you create a Handler and then use the post(), postAtTime() or postDelayed() methods. You can also queue your own "events" to the Looper, by posting "messages" to the Handler. If you do that, you'll need to provide code that actually does something with the messages once they get dispatched.

Be aware that the Looper on the main thread also dispatches all of the lifecycle events (like onCreate(), onResume(), etc.) and all of the UI processing, so that you can't have any long-running operations on it, otherwise your UI will be slow and sluggish and Android may just kill your app due to unresponsiveness. If you need long-running operations you will need to use separate background threads (look at Service, AsyncTask or just create your own Thread.

Solution 2:[2]

Activity in Android app is used to provide user interface. User interact with things like button, check boxes, edit fields to interact with app using Activity.

A Service is an application component that can perform long-running operations in the background and does not provide a user interface

You may need a Service, which do not supposed to have a UI and is created to perform background work for App. For example: Play song in Background in Music App.

In Your case, you should create a Service, use a separate thread that do the work of increment value. Check if "x" exceeds value in this thread.

Solution 3:[3]

There is not main loop in android but every time an activity is open it pass threw the on create you can do that a counter is increase every time the onCreate is called for more information about the activity life cycle look here Android Activity

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Wasser
Solution 2 zerocukor287
Solution 3 dorbt12