Running code in main thread from another thread

前端 未结 16 1886
一个人的身影
一个人的身影 2020-11-22 13:50

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

相关标签:
16条回答
  • 2020-11-22 14:36

    for Kotlin, you can use Anko corountines:

    update

    doAsync {
       ...
    }
    

    deprecated

    async(UI) {
        // Code run on UI thread
        // Use ref() instead of this@MyActivity
    }
    
    0 讨论(0)
  • 2020-11-22 14:37

    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.

    0 讨论(0)
  • 2020-11-22 14:39

    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.

    0 讨论(0)
  • 2020-11-22 14:40

    The simplest way especially if you don't have a context, if you're using RxAndroid you can do:

    AndroidSchedulers.mainThread().scheduleDirect {
        runCodeHere()
    }
    
    0 讨论(0)
提交回复
热议问题