how to manage jobs in job queue in android? - android

I am working on JOB queue. Here the scenario is i am storing 3 api calls in job queue. The first API is having more information in json. but last two is having less information. According to the priority when network is available it is calling those apis one bye one in right order. but as the first api is having more information it is taking more time to hit the server so it is reaching the server at last. Is there any way where after hitting the server we can able to run the rest APIs?

To manage your network request one after other you can Use AsyncTask.
AsyncTask have 3 main method i.e
1)onPreExecute - can perform any Ui update while calling network request.
2)doInBackground - which run in background thread not on main thread.
3)onPostExecute - after doinbackground process onPostExecute will call.
like this you can call your request when first request get completed ,So on first onPostExecute , call second request and so On.
I hope like this you can manage your network request in serial way. Thanks :)

Related

Multithreaded HTTP Request Queue System Approach

I've read alot of different recommendations on how to use locks - but the behavior of my current code in both IOS and Android does not behave correctly.
What I'm trying to do is build a queue system with a HTTP Request. If a Request fails, it should be the first request to be retried. Both send and add to queue is in the same method, so it shall not add a new object into the queue until the previous request has finished. If one fails and when the next request gets added it would send two requests (in the same package and clearing the queue).
Android:
// Java
synchronized(locker)
{
Add object to a queue if there is a new object to be added
If any objects in queue - send request with AsyncTask
}
IOS:
// Objective-C
#synchronized(locker)
{
Add object to a queue if there is a new object to be added
If any objects in queue - send request with NSURLSessionDataTask
}
...and on fail, do not remove the object from the queue.
In this case - I am guessing that the lock does get released and another thread could possibly be sending the next request right away and come first since the tasks are dispatched in another thread?
I've tried with normal locks with some success on Android and complete failure on iOS where the entire system freezed up. Since then I've read about locking a lock on IOS that it has to be unlocked by the same thread - would a dispatch_async(dispatch_get_main_queue()... on the entire method work or would I have to dispatched it again when the completitionHandler finishes? Can I be certain that the completitionHandler is called on the same thread as the method creating it?
It's very important that each package are sent in the correct order. What is the best approach towards a multithreaded HTTP Request system like this?
Don't spawn new threads by AsyncTask or NSURLSessionDataTask. If you need the threads to serialize, i.e. at most one of them may run at the same time, and the next one has to wait for the first one to finish completely, there's absolutely no reason to run multiple threads.
You're going to want one (1) thread for all requests, and maybe send data to it using a queue. Otherwise, the UI might freeze while sending http requests.

Waiting for a server task to complete

I have a situation where I have to do a server call from Android and based on the result of the call ( result would be either true or false) I want to proceed ahead in the code flow and pop a Dialog based on this result. Till the call is complete I don’t wish to proceed ahead in the code flow or logic. In short, I want to carry out a sync operation
At the server side, I will receive a HTTP Post request from android client and based on the parameters in the POST I do some processing by fetching values from the DB and return back true or false to android client.
To carry this out correctly on Android side, I researched and got two options.
Using Handler with AsyncTask does not work in my case because if
I use AsyncTask with Handler, the task result will arrive
sometime in future in Handler and the calling function will return
immediately whereas I want the calling function invoking
AsyncTask to finish i.e. wait till the server returns backs before I
proceed ahead .
The other option that I came across was to use
AsyncTask get() method . Since I am not carrying out a long running
task and rather performing a simple calculation on serverside, this
may not cause a an ANR situation even if I block the UI thread.
Are there any better options of carrying this out ? Is AsyncTask get() here actually one of the correct uses of get() ?

Android AsyncTask get() form another AsyncTask()

Background
I have an AsyncTask (call it uploadHeader) that uploads some data to a server.
I have a second AsyncTask (uploadDetail) that uploads some related data, which requires the initial data to have been uploaded: the header upload returns an id issued by the server, which is used to update the local detail records, before they're uploaded.
If at the time uploadHeader was initially called there were connectivity issues, the header info won't have been uploaded.
So at the start of uploadDetail.doInBackground() I check the status of the local header record to see if it has already been successfully uploaded to the server, and if not, call an uploadHeader.get() to upload the header and wait to get the id back, before I upload the detail records.
Problem
It just seems to hang at the get() call. Debugging it, it seems to be creating a FutureTask and then looping somewhere inside that. It looks as if the second AsyncTask is being queued to run after the first one finishes, which it never does since it's waiting on the second.
I've read a number of other posts/articles on calling one AsyncTask from another, but they all seem to be focused on getting the two to run in parallel. I want this to block, until the other task finishes. It's also been mentioned that "execute(Params...) must be invoked on the UI thread.", none of the articles mention get(). Or is get() basically identical to execute() apart for waiting for the result?
As a workaround, I could put the http call to upload the header in a separate class and call that from both uploadHeader and uploadDetail, so uploadDetail wouldn't need to create an uploadHeader task.
I'd just like to understand why it's not working as it is.
get() will block your execution until the second AsyncTask returns a value, don't do this if your first AsyncTask is doing some work that repercutes on the user interface of even in the workflow you've designed.
I'd definitely use Handlers on both AsyncTasks to communicate between them, even another one for the UI if you need to. You may find a good example here. For reference, look here.

asynchronous volley HTTP requests

As all requests in Volley are executed asynchronously on a different thread without blocking the “main thread”, is there any way to wait for the request to complete and then continue the main thread execution?
You should design your app such that it keeps the main thread live at all times. You can then have blocks of code run when the response has been received using listeners or async task. Check out my answer using listeners here. Or look at onPostExecute for AsyncTask.
is there any way to wait for the request to complete and then continue
the main thread execution?
An alternative is to show a loading dialog box while volley is working. This way you can prevent the user from interacting with your app until the request is completed (just don't forget to give him a chance to cancel).
Volley is meant to work in parallel with your main thread and tell you when the request has completed (what all apps should do) if you don't desire that, don't use Volley. But you'll get a NetworkOnMainThreadException and if you manage to bypass it, you'll end up with an ANR exception.

Android Asynk Task

is a good practice to have an Asynk task with a loop like this inside?
while (true) {
check queue and request API
Because i need to wait for my Activities and service needs to comunicate with the APi.
Thanks
I am assuming the "queue" is a Java queue, perhaps a LinkedBlockingQueue. If so, that queue is unnecessary, as AsyncTask has a queue to go along with its thread pool.
So, the question is: what triggers things to go in the queue?
If the trigger is a user event (e.g., menu choice, button push), just have it launch an AsyncTask, or have it have a Service launch an AsyncTask. That work will be queued up by the AsyncTask system.
If the trigger is the passage of time (e.g., we want to check an external server every 10 minutes), I would use AlarmManager and consider switching from AsyncTask and a Service to using an IntentService.
I have a priority queue in order to select first the important calls to the API.
My program have two services:
One calls the API when a message is added to the queue. The call to the api is made by an Asinc Task in this way:
messages.add(request);
new DownloadApiTask().execute();
The other service is updating the local database. For that, i have a loop in which i call the first service in order to get data from the API. The basic structure is:
while ihave data to updload
mFirstService.putMessage(request).
Fine, the problem is i have a rejected Execution Exception every X calls, I think it can be because i invoke the asinc task every time i take a message.
For that, i was thinking in force to the asinck task to check the queue instead executing it.
I hope you can understand my problem.
Thanks

Categories

Resources