Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

runOnUiThread from service [closed]

Tags:

android

I have a method in my service witch must be called from within a thread but I don't want that code to execute in the thread.

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

Thanks.

I am not interested in AsyncTask solution!

like image 932
opc0de Avatar asked Oct 03 '12 11:10

opc0de


2 Answers

Maybe a Handler can help you. Handler is an element associated to the thread where is created, you can post a runnable with your code to the Handler and that runnable will be executed in the thread where the Handler was created.

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

like image 83
Victor de Francisco Domingo Avatar answered Nov 15 '22 11:11

Victor de Francisco Domingo


The amount of words you are misusing is baffling. runOnUiThread is a helper-method to run code on the MAIN-thread. Normally, you use this method when you try to update your UI from a working thread. Since a Service doens't have a UI, runOnMainThread would seem highly inappropriate.

You question should be rephrased to either of the following:

  • How do I run my code off-MainThread?

Use an AsyncTask or an IntentService.

  • How do I execute code on the MainThread when I am currently in another thread. (Which normally in an Activity runOnUiThread can be used.)

Create a Handler on your Service his MainThread and post Runnables on it / send messages to it.

like image 23
DroidBender Avatar answered Nov 15 '22 10:11

DroidBender