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 ?
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.
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.
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.
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.
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.
runOnUiThread(new Runnable() { @Override public void run() { //execute code on main thread } });
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