Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 stumped as to how to do this.

I can't call this.runOnUiThread because "this" is an instance of Service, not Activity, and a Service doesn't have the runOnUiThread method.

I also can't create or execute an AsyncTask, because the documentation for AsyncTask says that both the constructor and the execute method must be invoked from the UI thread.

Do I need to maintain a reference to the activity that is using the service and call its runOnUiThread method, or is there another way to run something on the UI thread?

Thanks.

like image 947
Frank LaRosa Avatar asked Jun 25 '12 23:06

Frank LaRosa


People also ask

How do I run something on the main thread?

A condensed code block is as follows: new Handler(Looper. getMainLooper()). post(new Runnable() { @Override public void run() { // things to do on the main thread } });

Why should you avoid to run non UI code on the main thread?

All Android apps use a main thread to handle UI operations. Calling long-running operations from this main thread can lead to freezes and unresponsiveness. For example, if your app makes a network request from the main thread, your app's UI is frozen until it receives the network response.

Why should you avoid to run non UI code on the main thread in Android?

If you put long running work on the UI thread, you can get ANR errors. If you have multiple threads and put long running work on the non-UI threads, those non-UI threads can't inform the user of what is happening.


1 Answers

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); 
like image 90
harism Avatar answered Oct 12 '22 00:10

harism