Android asynchronous API design - android

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:
Taking a PendingIntent and sending it when an event happens (For example: UsbManager.requestPermission(), NfcAdapter.enableForegroundDispatch()).
Defining an internal callback interface and taking an instance of it, and then calling it when the event happens (Examples include View and its subclasses).
Taking a "broadcast action" as a String and then broadcasting that action (possibly locally using LocalBroadcastManager) (Example from IntentService documentation).
Having a purely synchronous API and letting the caller call it asynchronously (in an AsyncTask for example) (For example: SQLiteOpenHelper.getReadableDatabase()).
How should I design my API? And are there any recommendations for when to use each kind of API?

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.

Related

Android REST API with RetroFit

My question is kinda theorical, hope I can get a clear explanation on this.
I've been looking for a nice rest api consumer for android (or some clear info on how to develop a solid one) and I found the rest api design talk from google IO 2010.
"Developing Android REST Client Applications - Google"
It's been 4 since this talk and I think there might exitst new designs and techniques for this matter, or not ?
The scenario that I think that would work the best for me is this one:
So my first question is, does this architecture is still valid for a new app (Starting from the beginning) ?
I've found Retrofit, which seems a pretty nice and stable Api for the rest service, but I can't quite understand how it works, like if it is a good approach to call my api endpoints from activities (or frags) and the library handles the resume/pause (delivering results when activity is on hold, or not) or I must implement this myself.
Sorry for the long post and thanks for the patience !
You must implement how to handle that yourself, to answer your question.
Yes, that architecture is valid, but RetroFit only forms part of the "Rest Method" block. How would you implement it? That depend on what you want. You could use Retrofit (AKA the REST Method) inside the service, and that would be ok, however you can also skip using services and use it inside of an activity or fragment. However if you do the second option(activities/fragments) you can not think in handling the activity life cycle within retrofit(onStart, onPause, etc..) because since these are network calls, you must perform them on worker threads(AsyncTasks for instance).
So in conclusion, whatever option you decide, being Services or worker threads, you must think in using perhaps observers to control your activity/fragment, and remember that requesting network data is always done out of the ui thread. Implementations of how to handle the situation may be done by you depending on your needs and complexity of the application.

ContentProvider or Service?

I am writing an application that shows "Japanese Traditional Time" (JTT for short). There are several components (notification, widgets, application itself, alarms) which all use the same data - current JTT.
My current version uses a single service that does all the calculation and uses a Handler to notify everyone about "ticking", mimicking ACTION_TIME_TICK.
However with alarms I need to also have a way to translate "usual time" to JTT and vice versa. The calculations are quite CPU-heavy (it's all based on sunrises and sunsets) and thus I prefer having it all done in a single place and then cached (calculating stuff knowing sunrise and sunset times is not as heavy).
So I have several ways to do that now:
Keep it all in Service
And use binding to request the data I need. It's actually already done in one case and seems a bit cumbersome since I have to handle asynchronous responses
Move to content provider
And use content observers instead of broadcasting
Or send broadcasts from provider
Combine both ways
Use content provider to calculate the data for service which in turn will broadcast it when needed
Which would be better? Maybe something else?
Content providers are for structured data, so it doesn't really fit your use case. Not sure what you mean by 'asynchronous responses'? Calling a remote service is usually just like a local function call, it will block and return a value when done. If you have to notify multiple components a broadcast is the way to go. Explore using a LocalBroadcast if all components are in the same process (check Android support library source), or set a permission on it to make sure other apps cannot get it if you need to send a system-wide (regular) one.
I'm sticking with "just service" - I have discovered Sticky Broadcasts which actually cover the problem I had with common Broadcasts (having to request latest data from service after registering but before getting the first "tick") and that leaves me with much less cases where I need actual service connection.

What is the best threading choice in an Android application for a RESTful API passing JSON data?

I am new to Android. I’m attempting to write an application which will display multiple pieces of information about open stores. I get that information using a RESTfull API which passes JSON data.
Here is my question: What is the best service/threading implementation choice?
Here are my product requirements:
• I want to encapsulate all the API and JSON into a class that one or more Android “Activities” can call. I think this might dictate a service but this service will only need to run when my application is running and will not be accessible by other applications. The user will be required to authenticate into the remote system via the RESTfull API.
• It will have to be on a separate thread because of the possibility of the API calls taking too much time. I don’t think it will need to be multi-threaded since I don’t see more than one “Activity” will be interfacing with the service at a time.
• The service should look at caching some of the information it gets back so that when an “Activity” makes a call (“GetStoreList” for instance), it could return a list of stores it already queried earlier. I’m not sure if I should keep this information in memory or try using the SQLite functionality in Android. I could have several hundred stores in the list with ten to twelve other pieces of information associated with each store. Some of this information would be displayed in the “Activity” list view and some won’t. Since I don’t have any experience with SQLite, I’m not sure what the performance cost would be over storing the information in memory.
• There will be about a dozen or so methods that the service will need to encapsulate. For instance: once I get the store list, I may want to call the API again to find out if the store is currently open. Some of the information passed will be custom classes and therefore would require “Parceable” class definitions if I have to use IPC’s as part of my solution (if I understand the Android documentation correctly).
• I would also like to “Lazy-load” the list into my “Activity” so that I don’t have to wait for the full list before updating the user interface.
Possible Solutions (this is all guessing, so please don’t crucify me… that’s why I’m asking the question):
I could use a class extended from “Service.” It would have to handle the threading itself so that long internet calls via the RESTful API wouldn’t hang the system. Alternatively, I could do the thread manipulation first and call the API with the assumption that I can take as much time as I want. I think I would need to implement communication between the “Activities” and the service via IPC’s. This seems a little complicated to me. I’m not sure if I can use the “Messenger” class. It looks easier than the AIDL stuff.
I think I could use an “IntentService”. This would automatically create a separate thread and queue messages/tasks. I think I could communicate with the service (to get the lists of stores for instance) by “Binding” to the service. The problem I see is passing data back and forth and I’m not sure how I would cache the data between calls to the API since the service terminates after making the API call.
Anyway, I’d rather learn from someone who has already done this type of app instead of doing it the wrong way and coding it twice.
Thanks for the help.
AbstractThreadedSyncAdapter was made just for stuff like this. There's a fairly comprehensive (but complex example) here. Also, one of my favorite Google IO videos gives a pretty good overview of how to use it.
Your scenario is almost exactly the same as ours in my previous project. Here's what we came up with (I'm sure it's not original, but is patterned from one of those google io videos too)
A Service handles the request-response of RESTful calls to the server. This is triggered by the activity calling startService(Intent) that includes the parameters in a Bundle included in the intent. The Bundle contains information as to what API will be called, and what parameters are included.
The Service doesn't directly pass the result to the activity - instead it writes the result to an sqlite database. The activity will know that the transaction is finished by observing the db (via ContentObserver). Similarly, the Service can notify the activity once a transaction is completed via broadcast; the activity can catch this by registering a BroadcastReceiver - however the resulting data should still not be directly passed to the activity via Bundle, as there may be cases where the data is too large for the Bundle to contain (there's a limit for the length of a String that can be included in a Bundle) - you still want to put the result in the Provider. The activity should query for the data as soon as the Service notifies the activity that the result is there.
Additionally, you can include a "success" or "fail" flag in the Broadcast that the Service will throw for the Activity, so it will know if it still needs to query for result - this removes an additional overhead for failed transactions.
If you need to ask, No we didn't use AIDL for this architecture (but we did use it on another module that does facebook/ym chat over xmpp).
The "lazy-loading" I think can be asked in a different question, as it is an entirely different process.

Android communication between two services

I know that an activity can communicate with a local service using the IBinder interface; I am trying to find a way for communication between two services.
Specifically, I have my main service starting an IntentService to handle file uploads. I want this IntentService to inform back to the main service once it is done uploading, and before it dies.
Any ideas about how this would happen?
You have to use BroadcastReceiver to receive intents, and when you want to communicate simply make an Intent with appropriate values.
This way you should be able to make a 2-way communication between any component.
In Android, there is a special way of completing tasks like yours. Look at AIDL (it's not well documented in official docs, but there are some extra sources on the web). This is a way of implementing two-way communication between any components placed in separate processes. In comparison to BroadcastReceivers, using this you'd get direct calls and callbacks, that will be less dirty than relying on something would come from somewhere in BroadcastReceiver.
To reach the needed effect, you'll have to define an interface for a callback and an interface for performing actions (with a callback supplied, or register/unregister methods). Than, after you received some command using the second interface, you should perform the job and post back the result through callback. To reach the asynchronous completion add a key work "oneway" before method signature (return type). To separate in and out params (if you need it), use "in", "out" and "inout" keywords near params.
As it comes to restrictions, only primitives, arrays and parcelables (and parcelable arrays) might be transferred between processes.
To control your callbacks lifecycle and operations atomicity, use RemoteCallbacksList for storing registered callbacks and notifying recipients using the duplicate of your list got from beginBroadcast.
If you have any troubles, you're free to ask here.

What is the preferred way to communicate between applications on Android (service vs. intents)

What is the difference between these two ways of interaction between applications on Android:
Implementing service in app #1 and using it in app #2
Handling intents and posting answers to the intents.
Interactions are supposed to be asynchronous.
What are pros and contras for each?
It really depends upon what it is you're trying to achieve. In the case where - as you ask - interactions should be asynchronous, there's no reason why you couldn't use Intents. This way has two advantages:
If it's a "general" request (something like "pick a photo" or such...) then it gives the user (and the operating system) a chance to choose the most suitable application. It's quite feasible that App #2 as you named it doesn't actually exist on the target user's device (unless App #1 specifically depends upon it).
App #2 can really take its time over whatever it is you've asked. If it's a user-centred task, then maybe it wants to launch an Activity and get user input, or such.
If you're looking for more technical advantages to this method: you don't have to worry about App #1 depending on generated class code every time you change the interface. When you write an interface using AIDL (this is how you implement the service model you named "1") the ADT will go away and generate a bunch of classes for you which you use to expose your remote service. Problems arise when App #1 has a different version of these generated classes to App #2. (And believe you me, the error messages associated with these problems are less than informative).
On the other hand, that's not to say that you should avoid the Remote Service model altogether; it has many useful applications. This is where my explanation becomes a little "hand wavy" but hopefully you will understand the gist of what I'm saying. AIDL interfaces give you much more direct control over the services you're calling. Instead of launching an intent, bundling in a bunch of data, and dispatching it in the hope that it will reach the correct Service (or activity, or other handler), then be handled in the right way, and eventually a result will get back to you, you directly call methods within a Remote class. The methods you call in that remote class are the ones specified by the AIDL interface written within App #2 (which functions like a server) - but you will quickly start to have to think about things like threads. You're directly calling code that lives in another process - which means that a thread belonging to App #1 is being given access to objects and methods in App #2.
How you deal with the fact that App #1 is calling code in App #2 is pretty much up to you, but the way I use (and I believe the recommended way, although if someone knows different I hope they will correct me here) is to use a Handler within App #2. When App #1 calls the AIDL interface, the code it calls sends a message to a Handler living in App #2, which then gets called by a thread belonging to App #2 - meaning you know which part of your app is accessing which members etc.
There are obvious advantages to this control flow, and to me it feels more "API-ish" - but that's not to say it's going to fit everyone's purposes. My experience is also that programming via an AIDL interface is much more error-fraught and fragile. Although technically it's always just doing what you told it to do, it's quite easy to tell it to do something wrong - or worse, misunderstand what you've told it altogether. I would say: exhaust other routes before thinking about writing an AIDL service.
On the note of asynchronous calls:
If you simply call code in App #2 directly, it's entirely synchronous.
If you use a message-handling interface, things are a little different. You can then provide a second AIDL interface living inside App #1 that allows App #2 to give you callbacks (this is what happens in the example on the official AIDL documentation for Android).
So you've got there two very flexable interfaces to interact between two processes. Both are good for different purposes.

Categories

Resources