Android recuring task best option? - android

Good morning everyone,
I am sending data to a device from android each 40ms. Up until now, I have been using a while(true) thread and thread.sleep because I didn't know better :). Now I see I have a lot of "better" options like:
TimerTask
Asynctask
ScheduledThreadPoolExecutor
Which is the best one for my scenario? Keep in mind that there may be an exception thrown if the device disconnects so I will need to stop sending values until the connection is restored. Furthermore, the data must be sent at pretty precise intervals and it should, in no case, be sent less than 40ms before the previous one.
Thanks!

Plenty of options, however, just prior to that AsyncTask does not really belong to that list. Asynctask is simply used to perform an operation in a background thread outside of the main UI thread and not really used for scheduling repeating tasks.
For repeating tasks, the options are:
Android: execute code in regular intervals
Use a countdowntimer as the countdowntimer executes in the main thread (if that is what you want)
Or use a TimerTask.
My suggestion for your case is option 1 or 3.
-V

Related

How should I set up my Android Google maps application?

I have been working on an Android application that uses Google maps and then runs some lengthy network intensive operations in the background. Currently, I am using a thread to run them on and they take anywhere from 30 seconds to 7 minutes to finish. After watching a few courses on Pluralsight about AsyncTasks and Background services, I now know that threads should ideally not be used for anything taking more than a few seconds. I am now altering my solution to run live with GPS rather than taking several minutes to perform the operations. The goal is to update an array every OnLocationChanged event.
I am having trouble in thinking about how I could alter a global array every OnLocationChanged event while also accessing it from the UI main thread. What is my best option for accomplishing this? Would I be able to use a process or AsynTask to accomplish this or would I need to go client/server route? Where would the OnLocationChanged be called?
First off, onLocationUpdated is called on the UI thread. So you don't have to worry about multithreading there.
Secondly- if you have a variable that needs to be touched by two threads you just use a semaphore and take it before you need to access it on each thread, and release it when done. Make sure to keep that block of code as small and quick as possible. There's more advanced stuff you can do for high performance needs, but that's good enough for 99% of code.
Thirdly- as I mentioned in my comment, your understanding of threading is wrong. The UI thread should not be used for more than is needed. AsyncTasks should not run for more than a few seconds (as there's a single thread they run on by default, so running long would block other requests). But a Thread can run as long as it needs to, and should be used if it needs long term background processing.

Async task versus service to download data

I want to know which is better to download files, async task or service?
My app has eight buttons, which one starts one direfferent download (which download has ~10MB). When the user clicks on one button or more to download data is better to use async task or service?
Thanks!
In any case you should use AsyncTask because even service runs in the main (GUI) thread where no networking should be done. Whether to run the AsyncTask in a service or an activity depends on whether you want that download to continue in background.
all above answers have good points. but the life-cycle issue is the most important thing you should consider. for instance, let's say you use asyncTask. so the user starts downloading and suddenly he/she rotates the screen and because you tied the asyncTask life-cycle to activity another asyncTask operation will be kicked off and result in a compulsive 10mb download. so considering this you should use service and asyncTask together to maintain life-cycle issue and UI thread networking issue.
update: Intent-service is a better solution because it receives requests in its own thread and goes offline when it doesn't have anything to do
AsyncTask -- AsyncTask manipulate threads and/or handlers, if you can do that better with Looper and stuff why bother? AsyncTask is designed to be a helper class around Thread and Handler, and it should ideally be used for short operations (a few seconds at the most.).. how can you tell in production mode whether is not gonna take long? probably bad network, slow network,jammed network, phone restarting - and all these will probably make your downloading either corrupt or unfinished.. i am a user of apps, and i get pissed when i waste bundle on nothing..
if you ask me, use
Service
--Serviceis made to run irrespective of what app/screen is visible and make if communicate with the UI if only it is available if not continue with download and save it, AsyncTask does not constitute a generic threading framework. always use threads, its cool, we all love it.

Android: gps and handler

My application have to catch gps coordinates and send them periodically using an handler.
Within the onCreate method I do:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, this);
and with that the onLocationChanged starts working.
At the end of the onCreate, I start an handler that every 2.5 seconds do some stuff.
I think this could not be the right way to achive my target, because the onLocationChanged() is not executed in a separate thread, so if the handler executes the onLocation could not be executed.
EDIT
I do not know how to concurrently manage the retrieval of GPS coordinates (how to execute the onLocationChanged).
The timer runs every 2.5 seconds a task and at the same time the onLocationChange have to set gps values that I need in the timer.
I fear that there may be problems with the onLocationChange that may not be performed at all.
I thought to use a AsyncTask, but how to execute it?
Although you have edited your question still not clear to me what exactly is your concern.
I'll give you some background information about concurrency, and let's see if it helps...
What is it
First, concurrency means a software designed to have more then one thread. That doesn't means that more then one thread will run in simultaneous, which only happens if you have a device with more then one core. If the device only has one core, only one thread will run at a time, and the system will switch between them.
As soon as your system is designed to have more then one thread, you must ensure that all your code (and used libraries) that are dealing with shared objects are thread safe.
Why should I need it
The most common reansons why you would need to use threads are:
You have a heavy piece of code that could be split into parts, and you have a device with more then one core. In this case, you could have a performance benefict from having two (or more) simoultaneous running threads dealing with parts of the work.
You have a blocking operation in your code (i.e. read from a socket). This should be moved to a separate thread to avoid blocking all your program until socket.read() returns.
Finally and the most commun one in Android, any long run operation (i.e. more then a couple of seconds) should be moved to a different thread from he one used by the UI (user interface), to avoid pour user experience and/or the ANR error.
Your situation
You refer that you are using LocationManager and an Handler. None of these classes imply using a different thread.
LocationManager uses the callback onLocationChange() to run the code you define in the UI thread.
Handler runs the code in the thread where the handler is assigned to. So if you created your handler in the UI thread, the handler callback will be run there as well.
Only if you create a new Thread (or any other class that does the same) you have a real multi-thread app that requires you to be carefull with shared objects.
Hope it helps. Let me know if you need more clarification.
Regards.
You can use the AsyncTask for fetching data.
refer this question.hope you will find the answer.
How To Get Location Using AsyncTask

Multiple async tasks not executing properly

I am trying to start 6 async tasks at a time in onCreate() of the activity. But I noticed following:
a) If I stay on same activity all the async tasks' doInBackground() execute properly.
b) If I switch to some other activity, only 4 or 5 async tasks' doInBackground() executes. Last async task's doInBackground() never executes.
Can someone tell what I might be doing wrong. I am staring different asynctasks in a for loop. If I do this in onStart(), then all the async tasks are executed again if I switch to this activity. Please help.
Here is the sample code:
For(int i=0;i<7;i++){
webServiceTask= WebServiceTask.getInstance();
webServiceTask.execute("");
}
Maybe you should consider some of the following points:
Is the WebServiceTask retrieving any information that is worth persisting (i.e. not very volatile, with a high risk of the user requesting the same data over and over again): in that case you can offload your work to an (Intent)Service and communicate the result back to your app via a ResultReceiver, or a ContentProvider (just to name a few).
AsyncTasks are not guaranteed to run to completion if no Activity or Service is around to keep your app's process alive.
If it is ok that the WebServiceTasks run after eachother, then you can probably also change your code to use only one AsyncTask that sequentially performs those tasks. You can even consider implementing AsyncTask's progress reporting mechanism.
If the operations performed by the AsyncTask(s) have no meaning once the Activity is closed, be sure to .cancel() them in your onStop() or onPause() lifecycle methods.
Keep bullet 3 of Ed Rowland's answer in mind, which I also posted in my earlier comment to your question.
Happy coding!
You need a Service of some kind to keep your process alive after the user switches away. Once your activity loses focus, Android is free to shut down your process altogether. Or your Activity. Either will cause problems, particularly if you are using the context of an Activity that has been shut down.
The Right Thing to Do (tm) is to implement a Service, and pass the operations off to the service for execution.
There are any of a bunch of reasons why only four tasks are running concurrently. Off the top of my head:
HttpConnection pools connections to servers, and throttles the
maximum number of connetions to any given server to some reasonable
value. 4 sounds about right.
your target server is throttling the number of simultaneous connections.
Your thread pool isn't as large as you think it is. Starting an API 16 (I think) the default threadpool size is one thread! (!!) Rationale: apparently Android OS developers got fed up with Android app developers doing threading wrong. Is it possible your tasks are executing serially? That would more or less fit the symptoms you describe.
But that's kind of a separate issue.

Android how many threads can I have going?

I have an Android app that has separate things going on but are all basically threads (and definitely are threads to the Android debugger)
There are multiple animation listeners that loop and call each other
There is a countdown timer that is always counting down to zero after it is initiated
Now I need to consider adding more countdown timers. How many of these kind of looping processes can I have going on? In this particular implementation I am not concerned about performance, efficiency, etc, until it becomes apparent.
Insight appreciated
I would be very surprised to learn that you exhausted the number of threads you can use safely in an android application, as long as you are properly managing their lifetime and prevent "busy loops"and the like from occuring.
One thing I did learn though, I am pretty sure you can only have 5 asynctasks operational at any time, and they will arbitrarily continue to exist and get killed or respawned by themselves if you start new ones...ie if i turned an asynctask on then off five times the debugger will say 5 async threads operational, but I can continually toggle on and off as much as I want because the resource pool will kill the oldest dead asynctask.
There is no maximum that I know of. I can tell you, however, that you most likely don't NEED that many threads.
You can keep countdown listeners in a single thread using Android's Handler, specifically the postDelayed() method. Start a Looper in a separate thread, and use a Handler to manage the timeouts -- don't busy wait, or sleep-loop.
I don't believe countdown timer will create threads--it should simply add your task to a queue on your main thread from the looks of it.
All your listeners should take place on the same thread as well (there is a single thread that manages all listeners (for visible objects anyway).
So you probably aren't using anywhere near as many threads as you think you are. If you were creating a lot of threads I'd be worried--they are really hard to keep synchronized and may cost you a lot more than you'd gain, but with the structures listed I'd go ahead and allocate as many as you feel appropriate (but test for performance on a cheap device of course)

Categories

Resources