RunOnUiThread from service

I have a method in my service that should be called from a thread, but I do not want this code to be executed on the thread.

How can I call runOnUiThread if I have no activity and I call it from a service?

Thanks.

I'm not interested in the AsyncTask solution!

+6
source share
2 answers

Perhaps Handler can help you. A handler is an element associated with the created thread, you can send runnable with your code to the handler, and this runnable will be executed in the thread where the Handler was created.

Informational link: http://developer.android.com/reference/android/os/Handler.html

+7
source

The amount of words you abuse is incomprehensible. runOnUiThread is a helper method for running code in a MAIN thread. Typically, this method is used when trying to update the user interface from a workflow. Since a Service does not have a user interface, runOnMainThread seems quite inappropriate.

You should rephrase one of the following questions:

  • How to run my off-MainThread code?

Use AsyncTask or IntentService .

  • How to execute code on MainThread when I am now in a different thread. (Which is commonly used in Activity runOnUiThread .)

Create a Handler on your Service its MainThread and send a Runnables message to it / send messages to it.

+3
source

Source: https://habr.com/ru/post/926832/


All Articles