Search code examples
androidnative-codeandroid-looper

Alooper_addFd data parameter


I am not sure how this function works. This is prototype:

int ALooper_addFd(ALooper*looper, int fd, int ident, int events, ALooper_callbackFunc callback, void *data);

What is this 'data' pointer? If callback is not NULL, 'data' should be custom data passed to callback. But, if callback is NULL, what is 'data' parameter used for? Or it have to be NULL also, in that case?

Is there any detailed documentation about this? Thank you in advice!


Solution

  • It's a pointer to arbitrary data that you can set if you need it in your application.

    Apart from being sent as an argument to the callback, the data pointer will also be written to the memory referenced by the outData parameter when you call ALooper_pollAll or ALooper_pollOnce.

    You can see the Android Native App Glue as an example. In this case, the data points to an android_poll_source structure defined by the glue, and to make the glue translate the commands from the looper's file descriptor into input and APP_CMD events, you must call the process function in (android_poll_source *)data when you receive an event from the looper:

    int ident, events;
    struct android_poll_source *source; // source is the data here
    while ((ident = ALooper_pollAll(0, NULL, &events, (void **)(&source))) >= 0) {
        if (source) {
            source->process(source->app, source);
        }
    }