Reputation: 4152
I'm writing an Android library that is inherently asynchronous (waiting for events from a USB device connected to the micro USB port). Looking at how Android packages implement asynchronous APIs, I found a few different ways:
PendingIntent
and sending it when an event happens (For example: UsbManager.requestPermission(), NfcAdapter.enableForegroundDispatch()).How should I design my API? And are there any recommendations for when to use each kind of API?
Upvotes: 4
Views: 535
Reputation: 35960
The main question is whether you will desing an API that is synchronous or asynchronous.
Synchronous API
Asynchronous API
If you opt for a synchronous API, you're pretty much done ;)
But if you opt for the asychronous one, in Android case (as you listed already) - you'll need to decide how the API implementation will notify the caller about the asychronous action being completed (or status being changed etc).
The PendingIntent is ususally used for a limited set of actions (i.e. launch an activity or a service, or send a broadcast). I assume your library client will want to do more varied actions than that.
Broadcasting an action is an option. It will separate the client from the library by "the intent wall", though. So for instance if your library would like to return some complex data structure to the caller, this data structure would need to be parcelable to fit into an Intent. Broadcasting is also a way of, well, "broadcasting" something. This means that multiple listeners could pick the message up.
Having that said, I would prefer to use the pure Java solution with callbacks interfaces, unless there is a good reason to use Android-specific solution.
Upvotes: 1