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
for Kotlin, you can use Anko corountines:
update
doAsync {
...
}
deprecated
async(UI) {
// Code run on UI thread
// Use ref() instead of this@MyActivity
}
As a commenter below pointed correctly, this is not a general solution for services, only for threads launched from your activity (a service can be such a thread, but not all of those are). On the complicated topic of service-activity communication please read the whole Services section of the official doc - it is complex, so it would pay to understand the basics: http://developer.android.com/guide/components/services.html#Notifications
The method below may work in the simplest cases:
If I understand you correctly you need some code to be executed in the GUI thread of the application (cannot think about anything else called "main" thread).
For this there is a method on Activity
:
someActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
//Your code to run in GUI thread here
}//public void run() {
});
Doc: http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29
Hope this is what you are looking for.
There is another simple way, if you don't have an access to the Context.
1). Create a handler from the main looper:
Handler uiHandler = new Handler(Looper.getMainLooper());
2). Implement a Runnable interface:
Runnable runnable = new Runnable() { // your code here }
3). Post your Runnable to the uiHandler:
uiHandler.post(runnable);
That's all ;-) Have fun with threads, but don't forget to synchronize them.
The simplest way especially if you don't have a context, if you're using RxAndroid you can do:
AndroidSchedulers.mainThread().scheduleDirect {
runCodeHere()
}