How to call Main thread from secondary thread in Android?
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.
Using BroadcastReceiver So you can use it to update the UI on the main thread. For example. Send data from a background thread. This method is usually used to communicate between Android apps or Android apps with the system.
If you put long running work on the UI thread, you can get ANR errors. If you have multiple threads and put long running work on the non-UI threads, those non-UI threads can't inform the user of what is happening.
When an application is launched in Android, it creates the first thread of execution, known as the “main” thread. The main thread is responsible for dispatching events to the appropriate user interface widgets as well as communicating with components from the Android UI toolkit.
The simplest way is to call runOnUiThread(...) from your thread
activity.runOnUiThread(new Runnable() { public void run() { ... do your GUI stuff } });
My recommendation to communicate threads in the same process is sending messages between those threads. It is very easy to manage this situation using Handlers:
http://developer.android.com/reference/android/os/Handler.html
Example of use, from Android documentation, to handling expensive work out of the ui thread:
public class MyActivity extends Activity { [ . . . ] // Need handler for callbacks to the UI thread final Handler mHandler = new Handler(); // Create runnable for posting final Runnable mUpdateResults = new Runnable() { public void run() { updateResultsInUi(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); [ . . . ] } protected void startLongRunningOperation() { // Fire off a thread to do some work that we shouldn't do directly in the UI thread Thread t = new Thread() { public void run() { mResults = doSomethingExpensive(); mHandler.post(mUpdateResults); } }; t.start(); } private void updateResultsInUi() { // Back in the UI thread -- update our UI elements based on the data in mResults [ . . . ] } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With