Running code in main thread from another thread

前端 未结 16 2109
一个人的身影
一个人的身影 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: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.

提交回复
热议问题