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
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
}
});