Should I use a listener interface or handler for event callbacks in Android development?

I am new to Java, I am porting our Windows Phone 7 library to work on Android. Due to syntactic similarities, this was very simple. Our library is basically an abstract HTTP message queue that provides persistence and data integrity on mobile platforms. It provides only asynchronous methods that are design choices. In WP7, I use delegates to call a user-called callback when processing an asynchronous message and server response.

To achieve the same thing on Android, I have found two ways so far - a simple Java listener interface that contains the OnSuccess and OnFailure methods that the user must implement, or using the Android handler class, which provides a message queue between threads (http: / /developer.android.com/reference/android/os/Handler.html).

I went with Handler at this point, as if I was honest, it looks more like a C # delegate. It also seems like less work for the user of our library. An example of some user code for using our library:

connection.GetMessage("http://somerestservice.com", GetCallback);

Handler GetCallback = new Handler() {
    public void handleMessage(Message message){
        CustomMessageClass customMessage = (CustomMessageClass)message.obj;

        if(customMessage.status == Status.Delivered) {
           // Process message here, 
           // it contains various information about the transaction 
           // as well as a tag that can contain a user object etc. 
           // It also contains the servers response as a string and as a byte array.
        }
    }
};

Using this, the user can create as many different handlers as he wants and call them as method parameters. Very similar to a delegate ...

, , , , Java, , , , , , .

, , , - , .. , , , , . , , , , , , ...

- , #, , , - Java - /? .

!

+3
2

- . , , , ( ) - , , .

, AsyncTask. ?

+1

, . , ?

, , , api, .

, , , getMessage.

, , Java . .

0

Source: https://habr.com/ru/post/1775103/


All Articles