imgx64
imgx64

Reputation: 4152

Android asynchronous API design

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:

How should I design my API? And are there any recommendations for when to use each kind of API?

Upvotes: 4

Views: 535

Answers (1)

kamituel
kamituel

Reputation: 35960

The main question is whether you will desing an API that is synchronous or asynchronous.

Synchronous API

  • API user will need to create a thread/AsyncTask (or similar) manually, so it's a bit more work on that side.
  • it's easier to misuse it - for instance by running a blocking method on the main thread
  • it's easier to reason about than the asynchronous API, because the code flow is streamlined and linear.

Asynchronous API

  • it's safer on the caller side (will never block UI)
  • tends to be (a bit) harder to use because of the callbacks (or intents, broadcasts listeners etc.)

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

Related Questions