I can see this has been asked before, but I am still struggling to find an answer.
I have a button that executes my AsyncTask. The AsyncTask has a loop that runs in the doInBackground, fetching some data from a server.
This all works really well, but it only works when a button is pushed at the moment. I want this to run every hour, after the button is pushed, until the user presses a second button that stops the process.
Can someone help me with how I can go about executing my AsyncTask every hour please?
I was trying to use a broadcastreceiver, but this wouldn't work and I read that this is not a good idea also.
The AsyncTask has a loop that runs in the doInBackground, fetching some data from a server.
A loop within doInBackground() is not an appropriate use of AsyncTask. AsyncTask is for "transactional" sorts of work, so the AsyncTask's thread can be returned to the thread pool in a timely fashion. If you want to have a Thread that runs for a longer period of time, use a Thread, possibly managed by a Service.
I want this to run every hour, after the button is pushed, until the user presses a second button that stops the process.
Use AlarmManager to set up your every-hour schedule. Please consider using inexact alarms to reduce the battery cost of this work. If you use a _WAKEUP-style alarm (e.g., ELAPSED_REALTIME_WAKEUP), you will need to use a WakefulBroadcastReceiver and an IntentService for your work, moving your doInBackground() logic from the AsyncTask to onHandleIntent() of the IntentService.
This sample project demonstrates the process, though in this case, the events are set up on first run of the app and on reboot. In your case, you would schedule the events and cancel the events when the button is pressed.
Related
I have a scenario in which 'N' number of independent code snippets need to be run repeatedly in a constant interval. Which one of the following will be more efficient?
One thread sending broadcasts repeatedly in a constant interval with N BroadcastReceivers registered for this action.
N number of threads running independently and running the code repeatedly.
Or is there a better method?
I would suggest a single background thread but not the methods you're suggesting.
Depending on your scenario:
If the code is to be executed frequently while the app is in the foreground, I would create a Handler associated with a working thread. Then use Handler.postDelayed() to post your work for future execution. When a Runnable finishes execution, it should repost itself.
If the code is to be executed in the background, use AlarmManager to schedule work to be executed by an IntentService and use inexact repeating when possible so that the system will batch background work to save battery life. IntentService will automatically create a single background thread to handle your work and process the Intents in sequence, then stop when it's done.
I am a beginner of Android Programming, and when I learn something about Service ,the problem has become.
We all know that the UI thread cannot run a long-time process, so we should run them in a new thread, and immediately ,we have recognised that something about Handler AsyncTask and Service even send a BroadCast when the task has been finished.However, I am not sure when to use them.
For example, we often using an activity to login, when the data should be posted, maybe post to the remote server, it may cost a long-time,we cannot write something in LoginActivity maybe in an AsyncTask or a Service to do that.But which is the better choice ?
As a general rule:
A service is running in background and does some (periodic) work for
you. For example if you want to fetch news from a REST-API every 15
minutes and informed the user within the app or with a notification
than use a service.
An AsyncTask is an separated thread for work intensive jobs to
prevent the UI thread from blocking. For example fetch the news after
the user clicks the "Get News" button.
In your case, the expectation of the user is important. The user tries to login and waits in an activity for the responds of the server. You should send the request to the server in an AsyncTask and e.g. show the user a waitscreen until the response is there ("Try to login"). So the UI is still responsive but the user clearly knows, that he has to wait for a response.
A service is running all the time on background on your device.
An AsynkTack is launch when you need it and executed in background. When it's done, the thread is destroyed.
Services - A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface.A service is a task with no UI.Runs always on main thread and can also block main thread.We can start service by calling method startService()
AysnTask - The AsyncTask class allows to run instructions in the background and to synchronize again with the main thread. It also reporting progress of the running tasks.Used for task in parallel.We start it by calling method execute().Wrok on worker thread and triggered from main thread.It can not run in loop.
I have implemented the class "trick" about differentiate between execute() and executeOnExecutor() but I ask myself how my app would behave in my concrete scenario.
In my activity I have 2 AsyncTask. One of them is an animation that is always running on background. Never stop until activity closes. I had to do so, with an AsyncTask, because I could not make work with Android Animation class. It is an infinite background scroll.
In the other hand I have an AsyncTask that downloads a file from Internet.
Due to before Donut AsyncTasks run serial, how my app would work considering the first task is always running on background and the second could stop when finish download?
If they execute serial, as the first task is always running, it would let the second execute some time? I think the app would never execute the second.
Would it work so? How I could solve? Would I forced to do in only one?
I started learning android i've been playing with it and so far so good but i have some doubts about Services, i started learning them today so by gently if a say something very wrong.
For example, i want my app to grab some information over the internet from time to time, this polling period is defined by the user, then the UI gets updated. I though about creating a Service that run lets says every 30 minutes, gets the information and updates the UI.
If i get it right:
An IntentService just executes an operation and stops by itself sending the result through an intent(right?), so i think it's not what i want.
A Bounded Service is most likely used when you want IPC or allow binding from external apps, which again i think it's not what i want.
I think a Local Service is probably what i need, using a LocalBroadcastReceiver to update the UI, how can i make it to run the operation every X minutes( Handler postDelayed, ScheduledExecutorService or Alarm Manager ? )
If i understand it right a Service if not bounded can run infinitely if it's not killed due to low memory problems, making it a foreground Service is the safest ?
Last thing and it's kind of a noob doubt, if the user leaves the application(Click Home Button or opens other app) the app is still in background but the activities are in "Paused" or "Stopped" mode will the Service still be able to talk to them ?
Sorry for long post and thank you.
Your requirement : after every x minutes, start a service, pull some date, update UI.
Solution :
Define or set an alarm for every x minutes, to trigger a receiver.
From receiver start the service.
In the service, start an async task to fetch the data in doInBackGround().
Once data is fetched, from onPostExecute() send a broadcast to your activity.
In the activity have a dynamic receiver registered for broadcast sent from service.
From dynamic broadcast receiver update UI.
From what you've explained I wouldn't personally use a service.
The Android docs on services explain more but here is a snippet:
http://developer.android.com/guide/components/services.html
A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
You could perhaps looks at using an AsyncTask, especially given that you only want it to run whilst the app is running:
http://developer.android.com/reference/android/os/AsyncTask.html
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
There is a good answer here on how to run an AsyncTask repeatedly at specific time intervals: How to execute Async task repeatedly after fixed time intervals
I've developed an application and one of its aims is to upload a file to the server. On average the file is quite large and upload takes a lot of time, so to make sure it'll be processed till the end, I moved the critical part of IO to the IntentService. From the IntentService for every single upload there's an AsyncTask started which does the IO job. Unfortunately the screen scrolling gets freezed several times while doing the upload in the background. I thought that a combination of IntentService+AsyncTask should be enough...
I'd be grateful for any suggestions how to solve it..
I think you may be misusing IntentService. I am assuming that you are calling AsyncTask.execute(...) from IntentService.onHandleIntent(Intent).
IntentService was created to perform background tasks one at a time on a non-UI thread. This means that onHandleIntent(Intent) is invoked from a background thread and should not be creating AsyncTasks. Furthermore, once onHandleIntent(Intent) finishes (and it does so immediately if all you do is start an AsyncTask) the service is a candidate for being shut down.
I know that this doesn't directly answer your questions but it may point to the causes of the issue.
Note that if you need to be able to handle multiple requests concurrently then your best bet is just to extend Service and enqueue a work request onto an Executor in onStartCommand(...).
[EDIT] For more information on proper usage of IntentService check this out.