Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Callback On Main Thread

Tags:

I have some code that interacts with the Android Facebook SDK, Asynchronously. Unfortunately this means when it returns it is in a background thread.

Cocos-2dx prefers me to interact with it in the Main Thread, especially when doing things like telling the Director to switch scenes (As it involves Open GL)

Is there any way to get some code to run on the Main thread ?

like image 949
James Campbell Avatar asked Oct 14 '13 18:10

James Campbell


People also ask

In which thread Does callback run?

This main thread, also called the UI thread, is also the thread that calls all click handlers and other UI and lifecycle callbacks. The UI thread is the default thread.

Can we execute network calls on the main thread?

Network operations and database calls, as well as loading of certain components, are common examples of operations that one should avoid in the main thread. When they are called in the main thread, they are called synchronously, which means that the UI will remain completely unresponsive until the operation completes.

Are CallBacks threaded?

Threading and CallBacks - they are related in that they both involve processing blocks of code or functions. Callbacks can be called in the primary thread of a program, interrupting that main program, or they can be called on a different thread so the callback is processed while the main program continues to run.

What is a network on main thread exception?

NetworkOnMainThreadException was introduced with Android 3.0. In an effort by Google to ensure apps stay responsive, NetworkOnMainThreadException is thrown when your application tries to access the network on the UI thread.


2 Answers

As long as you have a Context, you can do something like this:

Handler mainHandler = new Handler(context.getMainLooper()); 

And to run code on UI thread:

mainHandler.post(new Runnable() {      @Override     public void run() {         // run code     } }); 

As suggested by kaka:

You could also use the static Looper.getMainLooper() which

Returns the application's main looper, which lives in the main thread of the application.

like image 160
cYrixmorten Avatar answered Nov 02 '22 22:11

cYrixmorten


runOnUiThread(new Runnable() {     @Override     public void run() {         //execute code on main thread     } }); 
like image 23
Lefteris Avatar answered Nov 02 '22 22:11

Lefteris