Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do android's Event Listeners work?

How is an event captured from a View object? There is only one thread running : the UI thread (when we haven't implemented any of our own threads). Suppose if I have implemented an onClickListener for a button and this button's function is say "cancel". For the event to be raised by the button i.e., cancel whatever the UI is doing, it must interrupt. So is that it? Do they work like interrupts?

The API guides at the developer site are beautiful explanations but still don't give the complete picture. http://developer.android.com/guide/topics/ui/ui-events.html

like image 532
Frozen Crayon Avatar asked Jan 13 '23 18:01

Frozen Crayon


1 Answers

Internally, Android is running an event loop to handle UI events. For a nice diagram, see a third slide of this presentation. This thread is being used to dispatch system calls to the UI elements:

The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread.

(source: Processes and Threads)

Have a look at a Inside the Android Application Framework video from Google I/O 2008. It has the nice explanation of the event loop (consisting of Looper and Message Queue). The interesting stuff starts at around 26m into the video.

The onClick() method will be called from the same thread from which the original setOnClickListener() was called. If it was a main/UI thread, then you should be vary of performing long-running tasks in the listener - they will block the UI thread and can cause the app to be non-responsive. Use solutions like AsyncTask instead.

Please look at this blog post for detailed tutorial.

like image 101
kamituel Avatar answered Jan 21 '23 08:01

kamituel