Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running code in main thread from another thread

In an android service I have created thread(s) for doing some background task.

I have a situation where a thread needs to post certain task on main thread's message queue, for example a Runnable.

Is there a way to get Handler of the main thread and post Message/Runnable to it from my other thread?

like image 450
Ahmed Avatar asked Jun 20 '12 16:06

Ahmed


People also ask

How do I run something on the main thread?

A condensed code block is as follows: new Handler(Looper. getMainLooper()). post(new Runnable() { @Override public void run() { // things to do on the main thread } });

How do I switch to main thread in Java?

The main thread is created automatically when our program is started. To control it we must obtain a reference to it. This can be done by calling the method currentThread( ) which is present in Thread class. This method returns a reference to the thread on which it is called.

How Stop main thread while another thread is running?

You can not stop the main thread while any other thread are running. (All the child threads born out of main thread.) You can use function Thread. join() to keep the main thread waiting while other thread(s) execute.

Does main count as a thread?

Non-daemon vs daemon threadsThe main thread is a good example of a non-daemon thread. Code in main() will be always be executed until the end, unless a System. exit() forces the program to complete.


1 Answers

NOTE: This answer has gotten so much attention, that I need to update it. Since the original answer was posted, the comment from @dzeikei has gotten almost as much attention as the original answer. So here are 2 possible solutions:

1. If your background thread has a reference to a Context object:

Make sure that your background worker threads have access to a Context object (can be the Application context or the Service context). Then just do this in the background worker thread:

// Get a handler that can be used to post to the main thread Handler mainHandler = new Handler(context.getMainLooper());  Runnable myRunnable = new Runnable() {     @Override      public void run() {....} // This is your code }; mainHandler.post(myRunnable); 

2. If your background thread does not have (or need) a Context object

(suggested by @dzeikei):

// Get a handler that can be used to post to the main thread Handler mainHandler = new Handler(Looper.getMainLooper());  Runnable myRunnable = new Runnable() {     @Override      public void run() {....} // This is your code }; mainHandler.post(myRunnable); 
like image 148
David Wasser Avatar answered Sep 20 '22 17:09

David Wasser