Execute code on main thread in Android without access to an Activity?

后端 未结 5 1790
一整个雨季
一整个雨季 2020-12-16 10:32

I have an Android service that starts and maintains a background thread.

From time to time, the background thread needs to do a callback on the main thread. I\'m stu

相关标签:
5条回答
  • 2020-12-16 11:13

    For Kotlin:

    Handler(Looper.getMainLooper()).post { 
        /*My task*/ 
    }
    
    0 讨论(0)
  • 2020-12-16 11:13

    If you code in Kotlin you can use coroutine with Main dispatcher:

    private fun runOnUiThread(block: () -> Unit) {
        CoroutineScope(Dispatchers.Main).launch { block.invoke() }
    }
    

    Of-cause coroutines should added to your project as a dependency.

    0 讨论(0)
  • 2020-12-16 11:18

    Sure. See Handler. You can give to your service a handler object and when service needs to run some Runnable task on UI thread just must call handler.post(some_runnable_task). This call. Can find a example in this link 4.Tutorial: Handler.

    0 讨论(0)
  • 2020-12-16 11:30

    I'm using following code from time to time if I do not hold direct access to Activity (for a reason or another);

    new Handler(Looper.getMainLooper()).post(mYourUiThreadRunnable);
    
    0 讨论(0)
  • 2020-12-16 11:32

    Your activity has to can bind to the service.

    http://developer.android.com/guide/components/bound-services.html

    Specifically, take a look at creating a Messenger on that page. The client activity can give a messenger object that responds to messages from the service, and once received, run whatever UI code is necessary on the UI thread using a handler.

    DO NOT keep the activity's reference in the service. This can lead to all sorts of memory issues.

    0 讨论(0)
提交回复
热议问题