Today I was looking for this and Mr Brandon Rude gave an excellent answer. Unfortunately, AsyncTask
is now depricated, you can still use it, but it gives you a warning which is very annoying. So an alternative is to use Executors
like this way (in kotlin
):
val someRunnable = object : Runnable{
override fun run() {
// todo: do your background tasks
requireActivity().runOnUiThread{
// update views / ui if you are in a fragment
};
/*
runOnUiThread {
// update ui if you are in an activity
}
* */
}
};
Executors.newSingleThreadExecutor().execute(someRunnable);
And in java
it looks like this:
Runnable someRunnable = new Runnable() {
@Override
public void run() {
// todo: background tasks
runOnUiThread(new Runnable() {
@Override
public void run() {
// todo: update your ui / view in activity
}
});
/*
requireActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// todo: update your ui / view in Fragment
}
});*/
}
};
Executors.newSingleThreadExecutor().execute(someRunnable);