Android: Polling for every 2 sec - android

One feature of my application is to retrieve live data (JSON object) every 2 sec and display it (only while app is in foreground). I am executing an async task for every 2 sec. But this is making the app slow. I have searched for alternative, but i only got C2DM option. I can't use it because of server limitations. Could you please tell me an alternative or effective way for polling?

One option, if you have control of your server, is that you can switch to something like Comet (long-held http requests) to avoid the necessity of ongoing polling requests.

change the execution of the async task from every two sec to after getting the response for previous update you can initiate it in onpostexecute function... this will make your ui faster
also try using gzip so that the data gets transferred faster do not pool async task
your ui is getting slower as an async task is shot up before the previous one ore ones have completed

Related

Calling Asynctask in a queue

I am working on an app and want to send some data to server. I was able to send the data to server when the updates that I was sending to server were periodic.
But now Its upon user interaction. I have to send 1 or more calls to server. I cant skip and omit any call towards server. Just suppose the following case:
Case:
Let say I have a button on its click I launch a asyntask that put some data on server and let suppose it takes 5 to 6 seconds. But I want to trigger multiple asyntask , if user press the button multiple time. Let suppose he presses the button 7 time in a row. so the 7 AsyncTask must run in a queue one after an other.
I have heard about schedular and all others but I am unable to understand how to work with them using asynctask as well.
Possible solution : I can disable button until and unless first Async task is not completed, But I really do not want to do it, because under the requirements and needs I have to call async task as many times as user presses the button.
please help me, any source code will be appreciated.
Note: With asynctask I have nothing to update the UI.
Update :
under my need I want to queue the asynctask with specific data and it must automatically run when the previous task is completed and if user exit the application it should continue running until and unless it completes the execution of all queued asynctask.
Let suppose he presses the button 7 time in a row. so the 7 AsyncTask must run in a queue one after an other.
Depending on what API your app target you may simply need to do nothing special. Official documentation reads:
Order of execution
When first introduced, AsyncTasks were executed
serially on a single background thread. Starting with DONUT, this was
changed to a pool of threads allowing multiple tasks to operate in
parallel. Starting with HONEYCOMB, tasks are executed on a single
thread to avoid common application errors caused by parallel execution
therefore starting from Android 3.0 execute() is all you need really, which means unless you support ancient versions of the platform you should be seeing serial execution by default.
Alternatively, you can drop AsyncTask in favor of IntentService which are executed one after another.

How to use RxJava for asynchronously executing a dynamic list of consecutive dependent operations?

I'm working on an Android Service Library (AAR) that has to execute a variable number of processes consecutive/pipelined on an input (JSON) in the background.
Thereby, the next process takes the output of the previous process as input.
The processes can involve literally every kind of possibly long running tasks (http requests, IO/DB requests, heavy data crunching, ...)
It shall be possible to log the progress between every process and get the final output of the last process e.g. in a subscriber (library service thread).
The processes should run stable, in case internet connection is lost or parent application state is changing.
I'm currently using Robospice in my library to achieve stability for multiple requests...
This question: How to implement a sequence of consecutive operations using rxjava
is related to my question, except I ask for a variable sequence of operations.
Is it possible achieve this with Rxjava? If yes, how? If not, what are other options?
My idea how to do it somehow without Rxjava:
Keep Process count for every request
Processes[counter].execute(result, callback)
Callback-OnSuccess(result): increase process counter and start Processes[counter] with result
But I'm not experienced with thread handling and think this is not very robust and maybe it doesn't even work or blocks the calling thread (what makes the library not usable for this time)

Best practice for android to send a text string to server

I am making a real-time location tracker android app.
Yes there are lot of duplicate questions but here is my scenario.
Device's latitudes and longitude are changing continuously, So I have to send the data to at server almost every 2 seconds.
http://myserver.com/tracker.php?lat=10&long=5&guid=123456
On the other side another device will be fetching the location continuously every 2 second
http://myserver.com/getlocation.php?guid=123456
I am new in android development but googled about GCM, Bacground services and asyncTask.
Battery drain is not a issue for now. and I concerned about background services too. What will be the best approach to send and fetch the data every 2 seconds ? using AsyncTask or something else ?
It depends, if your server knows which devices should fetch the data, you can best use Google Cloud Messaging, though there might be a small delay which you will not like. If you want to poll for the data in your devices than use a separate thread (or AsyncTask which is just a thread with some wrapper code).
Additionally you can also use long Polling see this question for some insight into that. But that is on the server side, and still requires a thread in your app. Inside a separate thread you can use runOnUiThread to update the user interface, or use the success and progress functions of the AsyncTask
You can use Async Task which is the Best approach which is followed in the community.You can use handler inside your code to call the Async Task after every 2 seconds
AsyncTask should ideally be used for operations that take few seconds. Some tasks keep the thread running for long time so in that case it is recommended to use java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

Async task for batch http requests

I need to make a batch of HTTP requests and feed the responses to a ListView one by one. I am using an async task and running a for loop of requests in a doBackgroundProcess method. Is that a correct approach? If not, please guide me to the best practise.
It's not entirely clear what you're trying to do. If you're doing the following:
Collect a set of HTTP requests
Send them.
Get back the results.
Post to an adapter backing a list view
Wait for the user to initiate the next set of HTTP requests
then I suggest you look into an IntentService. If your Activity goes into the background for any reason, AsyncTask will stop, but IntentService continues until it's done all its work.
I'd even suggest you stick your HTTP results in a content provider. It's best to persist data that takes a long time to retrieve. Your users will like you for it! You can also stop when you lose connectivity, and then re-start where you left off, if you have the data already. And if connectivity isn't available at the start, you can show users the most recent results.
Remember that the network isn't always available.

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