Google IO 2010 Rest Structure - android

I am looking to implement the Google IO Rest Structure part A - Using a Service API. So i have identified the following portions of the structure.
An interface that provides rest method.
A Processor Class that implements the above interface. There will
many processor Classes. Each Processor class will return a model
class type.
A Service Provider, that deals with a Single Processor. The data
returned from the Processor is handled by the Service Provider. This
will call the Processor Function, and obtain the data returned.
A SerivceProcessor that is a service class. There will be a
single class in the application. This will communicate with the
various SericeProvides based on the Bundle data passed to it.
Service helper that provides high level integration between the
Activity and the Service
Now i am not clear here. The Service has the data that has been requested. How to proceede further. How do i pass the data back from the Service to the ServicHelper. Put it in a Bundle with the tag BUNDLE_EXTRA ? For this my pojo would have to be either Serializable or Parceable. I know Serializable is a really bad option on the Android Platform. What other options are they. Would i be using a Broadcast Intent ?
Thanks for any help here.

You can do a couple of things.
notifying back to the service helper through intents (letting it implement a broadcast receiver). This might be a bad idea since with a single rest call you can get a lot of rows. In this case you should implement some sort of facility to put your pojos in the intents you are sending back (like a fillIntent/getFromIntent method)
inside the service provider, store the result data somewhere (sqllite, contentprovider, file) and just throw a broadcast intent that will contain only the requestId and the result of your call.
The service helper intercept the broadcast and notifies any interested activity that the request has been completed. The activity updates the ui according to that. In this case the servicehelper is used just to keep track of the ongoing request / notify the results.
In my opinion this approach is better because you keep the ui and the model separated, and you don't demand to the activity the storage of the data, and it's more "rest oriented".
Plus: some time ago I tried to implement this approach. It's not completed but you can check the service helper and the request / result intents here postman lib
A more mature and robust library is robospice, which is what I would use now if I had to deal with rest services.

Related

Best Practice for updating fragment with data object (DTO)?

My fragment represents dynamic information which is obtained asynchronously. I am interested in how to provide the DAO/DTO to the fragment. Should the fragment maintain a reference to the DTO? What about updates. Should it request updated DTO and be the listener on these async calls or request that the activity make the requests and then update the fragment when the async response arrives?
There isn't really a "best practice" way to do this in Android. There are many ways and many of them are valid.
My recommendation would be to create a service that keeps track of changes in the data and report back to the fragment that requires it. Should be careful with this and make sure the service is only active when required, otherwise we can get background tasks that drain the battery.
The simplest way to register a BroadcastReceiver when the fragment is visible (after onResume, remove in onPause). This is like the intent filters that you can set for activities in the manifest. Here is a nice example: http://www.vogella.com/articles/AndroidBroadcastReceiver/article.htmlz
Once the receiver gets the intent there are 3 possible ways to procede.
Create a DAO and access the data (possibly a bit slow)
Use a ContentProvider and receive the new items in the intent sent to the receiver
If your data is Serializable or Parcelable you can add the new new data to the sent intent. (Possibly the fastest)
UPDATE
There is a useful tool for this kind of task that I forgot to mention: Loaders
They provide a simple way to handle data sources (like content providers).

Is handling http calls from multiple intent services good approach?

I'm developing restful android application, but I'm still newbie to android, and I would like to avoid beginners bed structural design that would cost me troubles latter.
I've read lots of discussions about android services and restful applications, many of them contrary to each other, so I would like to know have I choosen a good approach.
Inspired by this presentation http://www.youtube.com/watch?v=xHXn3Kg2IQE I put my http requests into IntentServices, instead of the Async Task.
I've choose Intent Service because of:
as a services they are not sensitive to foreground/background switching like Activities (won't get killed).
Intent service provides work in separate thread, so the user interface stays responsive.
Since Intent Service cannot run multiple request simultaneously, I've "split" my domain into few groups and for each group I have written my Intent Service. (ends up in: one CRUD set -> one intent service)
This way I got that inside of a group can be only one request running at a time (And this is good for me, since this way it could never be executed for example update and delete at same unit).
And, on the other side, I can run multiple requests at the same time if they are from the other groups, and don't affect each other.
So basically, I have this:
one generic HTTPRequest class that builds requests from name value pairs
UserIntentService - creates user related requests and executes it by using HTTPRequest cass, and proccess request using UserProcessor. Notifies caller by intent with data.
CallIntentService - creates call related requests and executes it by using HTTPRequest cass
and proccess request using CallProcessor. Notifies caller by intent with data.
UserProcessor - parsing response
CallProcessor - parsing response
ServiceHelper - finds and starts right intent service
When using from activity, I use something like this: SeviceHelper.StartService (action, data),
and I get response by local BroadcastReceiver inside of the activity. I register receiver on the OnStart(), and unregister it on the onStop() method of the activity.
Is that a good approach?
Should I have only one IntentService for all calls?
Is it better to have one Service that runs all the time in background, instead of using Intent Service that has to be started for each request?
Is there any other things that can get bad with this approach that I'm missing?

Android: Singleton which is used between Activity and Service

im wondering if it would be a bad idea to create a Singleton that is used between some Android Activities and a Android Service. As far as I know the static fields, in my case the Singleton, is available as long as the whole Process is alive.
My plan is to use a singleton instead of Parcelable to share data between my activities and a Background service. So my Activity1 will add some data by calling MySingleton.getInstance().addData(foo); then I would sent an Intent to inform my Service that new Data has been added to the singleton. Next my BackgroundService would handle the intent and call MySingleton.getInstance().getLatestData(); then it would process the data (takes some time). The result of the service would next be "post" back by using the singleton and fire a broadcast intent, which are handled by the Activity1 (if alive) and the Activity1 will retrieve the result from the singleton.
Do you guys think thats a bad idea?
EDIT:
What I want to implement is an peace of software that downloads data from a web server parse it and return the result. So my Activity would create DownloadJob Object. The DownloadJob-Object would be put into the DownloadScheduler (Singleton) which queues and manage all DownloadJobs. The DownloadScheduler would allow to run 5 DownloadJobs at the same time and use a queue to store the waiting. The effective Download would be done by the DownloadService (IntentService), which gets informed over an Intent that the a new DownloadJob should now be executed (downloaded) right now. The DowanlodService would retrieve the next job from the DownloadSchedulers queue (PriorityBlockingQueue) and return the Result by setting DownloadJob.setResult(...) and fires up an broadcast intent, that the Result is ready, which will be received by the DownloadScheduler which would remve the job from the queue and inform the Activity that the download is complete etc.
So in my scenario I would use the singleton to access the DownloadJobs from the DownloadService instead of making a DownloadJob Parcelable and pass it with the Intent. So i would avoid the problem, that I have two DownloadJobs in memory (one on the "Activity Site" and one on "Service site").
Any suggestions how to solve this better?
Is it true that static instances, like DownloadScheduler(Singleton), would be used by freed by the android system on low memory? So would subclassing the Application and hold there the reference (non static) avoid this problem?
If you are using the singleton just as shared memory between a background service which I assume is performing operations on a different thread, you may run into synchronization issues and or read inconsistent data.
If the data in the singleton is not synchronized, you have to be careful because you are relying on your "protocol" to be sure that nobody is reading while your background thread is writing (which may lead to errors).
On the other hand, if it is synchronized, you are risking to face anr error because the activity which reads the data may be blocked waiting the service to finish to write the data in the singleton.
As the other said, you also have to keep in mind that your singleton may be freed if the os needs resources, and that your data may not be there anymore.
I'd rather use an event bus such as otto or eventbus
EDIT:
Using a singleton as the entry point of background (intent) service is the approach suggested in 2010 Virgil Dobjanschi talk about building rest client applications for android.
The suggested approach is having a singleton that performs as controller of ongoing requests. Please consider also that request to intent service are already queued by the os, so you can throw several intents that will be processed sequentially by the intent service.
Some time ago I also tried take that as a starting point for a library, which still remains unfinished. YOu can find the sources here
What I would certainly not do is to store your data in the singleton. The approach I would prefer is to store the data in some persistent storage (such as sql / preferences / file / content provider) and let the client know of the change through a broadcast message (or, if you are using a content provider, through an observer).
Finally, to some extent this is the approach followed by the robospice library, which looks quite mature and ships a lot of interesting features such as caching.
A better idea is to subclass Application and put any long living objects in there. By subclassing Application you can properly handle startup and shutdown of the application something you can't easily do with a singleton. Also by using an Application Activites and Services can share access to the models within your program without resorting to parcelables. And you can avoid all of the problems Singletons bring to your program.
You also don't have to resort to storing everything in a database which requires lots of boiler plate code just to shove a bunch of data in there. It doesn't do anything for sharing behavior between parts of your application and doesn't do anything to facilitate communication and centralization of activities. If you really need to persist state between shutdowns great use it, but if not you can save yourself a lot of work.
You could also look into using something like Roboguice which makes injecting shared models into your Activities and services.
You might find this helpful:
what's design pattern principle in the Android development?
Using a singleton like this is not necessarily a bad idea, but you will lose it's state if Android decides to stop your process. You may want to consider storing your state instead in a SQLite database or a persistent queue (take a look at tape for a good example).

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.

Categories

Resources