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.
Related
I am a Java developer with no Android experience, and I am trying to quickly put an app together. It seems that what I would normally do in Java isn't helping.
At this stage, ease of implementation is more important than efficiency or style - I will sort the latter out when there is more time and I will have educated myself properly when it comes to Android.
People can use the app to ask for support, or offer it to those who need it. Asking for support posts a request with the details to the server, and that's done.
Now I would like the app to post an asynchronous request to the server, to be notified of outstanding support requests once a minute. I guess it's the same principle of WhatsApp checking if there is any new message on the server.
I tried doing that in a separate thread with an infinite loop which sleeps for 60 seconds but for some reasons that stops the UI from working.
From what I now understand, I should use a service with a Looper, a Timer and a Handler. Is that correct?
Could anybody point me to a tutorial which explains exactly what to do, step by step? Or at least suggest keywords I should look for?
All I found so far are snippets of code which don't work together when I try to assemble it. Possibly because I am not searching for the right terms?
Thanks, Dan
You could try the following approach:
Create a service that runs in the background to check for newly added data in the server.
If you prefer to make it user-driven, you can let users refresh the list on the device to actually trigger the requests to the server.
Libraries like Retrofit can make your life easier when it comes to making http requests - always avoid the main UI thread when doing this.
Another library that you could use to decouple your application using Events is EventBus. Assuming you are running a background service to check for updates, you can use EventBus to update your User Interfaces when something new is retrieved from the server through a GET request.
I hope this gives you an idea on how to proceed with the solution. Good luck!
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
I'm using Fragments and LoaderManager. I have to launch an unknown number of tasks, and they might be run in parallel (otherwise I'd just reuse one and only one loader). For example, I have a listview, and each row might have a button to save the content of that row to a webserver. The user could initiate a save request on multiple items in parallel.
private int nextId = 0;
private void onClickListener() {
Bundle bundle = new Bundle();
bundle.putNextData(...);
getLoaderManager().initLoader(nextId++, bundle, this);
}
I could try bookkeeping myself, so create a pool of loaders manually and reuse them when possible, seems like it might be something already implemented by the API?
Thanks
I don't think you should use a Loader for saving data to a remote server.
Instead, use an IntentService or something similar to process a queue of "save" operations. This way, your communication with the web server can be batched, collapsed (i.e. multiple queued saves for a single item can be collapsed into one operation), and will live beyond the lifespan of your activity if need be.
A save queue processed by an IntentService (or equivalent) is also a great way to retry failed operations with backoff, since you can implement delayed retries with exponential backoff using AlarmManager.
An IntentService or bound service are always good approaches for that.
As Roman points, note that enqueuing several requests and called them separately is not highly recommended (it is very likely that you give a lot of work to the radio connection - when using data - which among other things drain your battery. Here is must-read about that)
I'd personally recommend to use a bound service with a queue of requests and a pool of threads available (that approach gives you full control for more complex network operations like in your case). There are more details on the approach here and a testcase working example over here.
Update us about your progress.
You are at the right direction, let me just help you a bit.
Reusing is indeed a good idea, and you do not have to worry about it because Android did it for you(Or Java actually ;)
It called ThreadPoolExecuter, you can start as many tasks as you wish and he will only open the predefined number of threads.(Best practice is trying to open as many threads as parallel network connection can be run on the device. From my research it is between 4 - 9).
And if you are trying to download same URL twice may be you can protect your self and open only one task for it.
I have an app that checks GPS position and interacts with four websites. I am thinking of using ASync tasks within a Service. The result from each website does not depend on any other website.
As finding the location and interacting with each website will take a different amount of time, does this mean I should have five services? Or should it all be combined into one service?
You need to call the other 4 services after you get a GPS fix. You can create new instances of each AsyncTask running in parallel. I don't see the need for using a service. I use one httpClient object stored in an application class for all web requests.
You don't need additional services. The problem here, as I understand, is that each HTTP call might take a long time to finish and that would slow down the whole process and that you will have too many ASynkTasks. Then, Google has already solved the problem for you.
Instead of using ASyncTasks you can use Volley and send all your requests to websites in parallel. That way, Volley will handle your requests in different threads and keep everything tidy. As a bonus it is A LOT faster than ASyncTask.
Handler or Listeners. What is better use for notification of event? What is faster, more efficient etc.?
That's a good question!
scenario for using a handler
I've got an Android background service running in my app that uses handlers exclusively for web communications - I decided to go this route because the handler will queue requests and execute them one by one so then I know that a sequence is remained intact.
For example, in an instant messenger app you might find it desirable to maintain a sequence for your chatting.
scenario for using a callback
My background service also uses a class that reads from hardware (in a separate thread); some data might come in at any time and needs to be processed immediately. For that class I implemented a listener/callback interface.
My only question is whether there's any etiquette for the size of the handler.
I have about 50 unique messages:
outgoing web requests consists of about 25 messages (each message is a different API on the web server)
Each API returns a response, therefore there's another 25 incoming web
responses
The handler requires about 60% of the service's code - as you can imagine this results in a very big switch(case{}) structure (almost 1000 lines of code). Too big? How to break it apart?
There's no such thing as a Listener type, it's just a naming convention for callback interfaces. So you just use them if you want to process your events synchronously on the same thread.
A Handler is however an Android class... you use it for passing messages and runnables from the thread raising the event (e.g. "download complete") to the thread that needs to handle it (e.g. the UI thread).