Best way to do Async server communications from multiple Activities - android

I'm having problems trying to find the best way to do two-way server communications, asynchronously. I am able to do the server communications hard coded to a server (no encapsulation, async calls), but I want to know what the best way to do it is. There's a protocol for logging in, registering, changing location, etc.
The server communications are using JSON and HTTPPost. The app would be sending JSON data and receiving it and putting it into a database.
I thought of making a ServerCommuncations class which holds data such as username, password, etc. and instantiates the HTTPRequest objects and other common objects. This could be inside a Bound service.
Now I could use a Bound Service with an AsyncTask, however multiple Activities in the app will need to do server communications so it would mean binding the service to multiple Activities.
Is this possible?
Is there a better way?
If I was to use the bound service, would it be best to use Messengers or extend Binder class?
What are your thoughts?

A possibility is to use IntentService for handling asynchronous code.

Maybe you could use a real Thread and pass it a handler which is a singleton. you could then use the handler in all your activites.

Related

Receiving responses in Android from a Spring REST service

I'm working with Android on the front end and I'm using Spring's REST Client libraries to send HTTP Requests to a REST web service. I've read examples online where people use AsyncTask to accomplish this with a RestTemplate in doInBackground method of AsyncTask, but I've also read examples where RestTemplate is used outside of AsyncTask, even in an activity or fragment. Is there any point in using one method over the other?
Secondly, when receiving a response from the server through RestTemplate's exchange or getForAllObject, based on the data received my client should be doing different things. For example, if I want to search for users, I should receive User objects and then my client should then update the users fragment/activity, but if I want to login, I should receive different data and my client should perform different subsequent tasks.
If I create an AsyncTask every time I send an HTTP Request and then receive the response, how can I distinguish what subsequent tasks need to be done client-side? Is the preferred method to use enums? For eg., when I want to get data from a server, I can instantiate an AsyncTask and pass as execute parameters an enum to specify which HTTP request to send and an enum to specify what to do with received data. Then I could just use switch statements which call different functions based on the enum?
If none of this makes sense, is there a more standard way to approach handling responses from the server?
From docs
AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask provides a convenient way to do tasks in background and interact with the main UI thread. If you did not use AsyncTasks you have to implement your own methods to synchronize with the main thread to update the UI. If you are calling any back end services or doing long running operations, it is always good to go with async tasks.
It is a bad practice to have your same REST end point to return different objects based on an enum. Have two separate endpoints. One GET call to search users and one POST call to login users. In the client side also have separate implementations on consuming above endpoints. Use them appropriately when needed.

Performing Request After Android Service Binding

I have a two part question. Both are somewhat general.
I'm creating an app that relies heavily on communication with a server. I plan to have different classes for each repository I'll need. Is an Android service the correct pattern to use here? There may be certain situations where I'll want to cache things between activities. Will a service allow me to do this?
Assuming a service is what I want to use for this, how can I load content once the service is bound. When the user opens the app, I want to start loading content. However, binding a service isn't blocking, so I can't write the code that makes requests with the service in my onStart() right? Is there some helper class that will wait for the service to load then execute a function? I know I could put some code in my onServiceConnected() method but I'd like to stay away from coupling like that.
Hopefully that wasn't too abstract. Thanks in advance.
Yes, Service is the way to go, but a started service, not a bound one.
You could make async request methods, and the Service can broadcast the result back to your Activity.
The async request in this case is a startService(intent) with an
Intent containing the request parameters. The service would start a background thread for the operation, optimally you can use a networking library for this (for example Volley).
And the reply is a broadcast by the Service with the relevant data.
This answers the problem of caching, because the Service can decide what to return. So in case the Service does not have the requested resource, it will download (and return) it. But if the Service has the resource, then it will just simply return the cached version.
To start, you should get yourself familiar with these topics:
Started Services (for the requests)
LocalBroadcastReceiver (for the reply)
Event Bus (alternative to LocalBroadcastReceiver, for example Otto)
I don't know much about your concrete needs, but it seems like you want to implement a REST client with cache. There is a really good Google IO presentation on that here. Definately worth to watch!
1)If you need code to run even when your Activity isn't, the correct answer is a Service. If you just need to cache data, then storing it in a global static variable somewhere may be ok.
2)Your service can start a Thread or AsyncTask. These execute in parallel. onStartCommand generally launches it in this case.
As with most things, the answer to these questions are subjective at best. I would need more information then I currently have, but I'll take a vague, general stab at this...
If you need something persistently hitting your server repeatedly I would say use a service.
Where you call it is not nearly as important as how many times it needs to be called. That being said the answer is yes. If you need this data as soon as the application or activity loads, then the onCreate method is where it needs to be loaded.
My reccomendation is either A) service or B)AsyncTask.
Go with A if you have to hit the server repeatedly for data and need it in regular intervals. Otherwise go with an AsyncTask and load all the data you need into an object for storage. Then you can use it as you need and it will essentially be "cached".
The difference between the two is simply "best tool for the job". I see you use some javascript. To give a proper analogy, using a service for a server call rather than an async task, is the equivalent of using a web socket (node js) when you could of just used an ajax call. Hope this helps. Oh and PS, please don't use static variables in Android =).

what is the best/preferred approach to implement multi-threading in android app

I'm a beginner in android development and I'm trying to implement an android udp client, which connects to a java server and sends/receives some packets from it.In this process it collects some data (like round-trip delay etc), which is used to measure the QoS of that particular network. I have tried implementing the connection and sending/receiving data using Java Threads, but the application crashes, and hangs if i try to use more than 2 threads. So I'm looking for alternatives. While going through this site as well as some other links I found that in android multiple threads can be implemented using AsyncTask, Handler etc. Also I found that the Service class also helps to run a background service in an app. Please suggest which approach among these would be the best to achieve my purpose.
Thanks in advance.
You can use AasyncTask to do this and as you mentioned service may be useful too, where u can let your application do whatever it wants in background , if user needs to use application by its interface then AsyncTask must be used to avoid Crashing
There is not one right answer that can be applied as a broad stroke to how to do Android multi-threading. There are a few different ways to approach it based on what your specific needs are.
Any long running, blocking call, in Android will result in the application crashing.
The most common solution is to use an AsyncTask though. For example, when I want to make a call out to a web API endpoint for some XML data within an Activity I would in this case use an AsyncTask and kick off the calls from within doInBackground.
This is not an appropriate solution though if the wait time is longer, or possibly an unknown wait time. Or in a situation where there will always be waiting such as a message queuing service. In this type of situation it may be best to write a separate app based on extending the Service class. Then you can send/receive notifications to/from the service from your primary application in a similar manner to how you would communicate with a web service.

Best Multi-threaded Architecture for an Retriving Data Over HTTP?

world!
I'm building an application that has to retrieve data from a server in several different Activitys. Some data is cached to a SQLite database (and retrieved from there instead in future), and some must be called fresh from the server every time. I need to know what the best multi-threaded architecture would be for this application. Multiple Activitys will be connecting to the server.
I'm thinking a bound Service would be best, but of course I'm not sure. If that's the way to go, how exactly do I implement multi-threading in it?
Thanks
The android classes such as IntentService and AsynTask are thread safest because they will not keep your activity open when your activity's finish method is called. If you create your own Thread implementation you must remember to stop the thread on Activity finish so that the process' memory will be reclaimed.
In a situation like yours I am going with a set of singleton factory classes to access local SQLite db and a background service doing asynchronous replication

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