Execute code on main thread in Android without access to an Activity?
android, multithreading
Solution
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);
Problem
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.