What are threads in Android

background

There are situations when operations from the main thread should be paged out into separate threads. For this, Android basically offers different approaches. This article is about a simple and lightweight implementation based on Handler and Looper walk.

implementation

First it comes to the implementation of the worker thread: For this, the implementation is based on a simple Java thread:

In the main thread of the application, the call is made via

In order to exchange messages between threads, it is necessary to give the receiving thread a MessageQueue. This is done using the class Looper. The static methods prepare () takes care of the creation of the message queue. With a call from loop () processing of the message queue is started:

Send and receive messages

In order to be able to receive and send messages, an instance of the type Handler needed. It is important at this point that the generated handler instance is automatically assigned to the generating thread. With implementation of the method handleMessage (Message) individual handling of incoming messages can be implemented.

So that messages can now be sent to this worker thread, the sender only needs a reference to the handler instance of the receiving thread. With a call from sendMessage (Message) a message can then be sent to the associated worker thread:

About Andreas Schrade

IT company owner and enthusiastic Android Developer expert who serve companies in all over the world. Intrigued by ideas, challenging projects, lifelong learning, armchair philosophy, and even better conversations.

Seeking to be inspired, to envision the unlikely, to work hard for things that are worth it, and to be surrounded by those who bring out the best in me.
Say hi!
on Twitter @andreasschrade
on LinkedIn andreasschrade
Contact me!

Comments

comments powered by Disqus