How to Define Callbacks in Android?

后端 未结 6 1024
太阳男子
太阳男子 2020-11-22 05:32

During the most recent Google IO, there was a presentation about implementing restful client applications. Unfortunately, it was only a high level discussion with no source

6条回答
  •  别跟我提以往
    2020-11-22 05:49

    to clarify a bit on dragon's answer (since it took me a while to figure out what to do with Handler.Callback):

    Handler can be used to execute callbacks in the current or another thread, by passing it Messages. the Message holds data to be used from the callback. a Handler.Callback can be passed to the constructor of Handler in order to avoid extending Handler directly. thus, to execute some code via callback from the current thread:

    Message message = new Message();
    
    
    Callback callback = new Callback() {
        public boolean handleMessage(Message msg) {
            
        }
    };
    
    Handler handler = new Handler(callback);
    handler.sendMessage(message);
    

    EDIT: just realized there's a better way to get the same result (minus control of exactly when to execute the callback):

    post(new Runnable() {
        @Override
        public void run() {
            
        }
    });
    

提交回复
热议问题