I am an iOS developer who just recently tried Android development.
In iOS I use Completion Handlers in my codes.
I am wondering if there is an equivalent of it in Android development?
Thank you
In android Handler is mainly used to update the main thread from background thread or other than main thread. There are two methods are in handler. Post() − it going to post message from background thread to main thread using looper.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .
If you need it for doing asynchronous operations then look into AsyncTask - this is a class where you implement doInBackground where your long operation is performed and onPostExecute method where code that is suppose to update UI is performed.
Now if you want to pass some special code to your AsyncTask to be performed after long operation you can:
(1) Pass an interface which would be implemented by your Activity/fragment, ex:
// Psedocode to reduce size!
interface MyInterface {
void doWork();
};
class MyAsyncTask extends AsyncTask<Void,Void,Void> {
MyInterface oper;
public MyAsyncTask(MyInterface op) { oper = op; }
// ..
public onPostExecute(Void res) {
oper.doWork(); // you could pass results here
}
}
class MyActivity extends Activity implements MyInterface {
public void doWork() {
// ...
}
public void startWork() {
// execute async on this
new MyAsyncTask(this).execute();
// or execute on anynomous interface implementation
new MyAsyncTask(new MyInterface() {
public void doWork() {
//MyActivity.this.updateUI() ...
}
});
}
};
(2) Use local broadcast receivers, EventBus, but those are more heavy weight solutions.
(3) If you already have some callback interface in you backgroung worker code then you can make it execute on UI thread using this code:
// This can be executed on back thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// do work on UI
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With