Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Completion Handlers in Android

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

like image 820
JayVDiyk Avatar asked Dec 16 '15 09:12

JayVDiyk


People also ask

What are handlers in Android?

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.

What is Handler in Kotlin?

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 .


1 Answers

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
  }
});
like image 66
marcinj Avatar answered Oct 05 '22 08:10

marcinj