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
For Kotlin:
Handler(Looper.getMainLooper()).post {
/*My task*/
}
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.
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.
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);
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.