Reputation: 741
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.
Upvotes: 1
Views: 172
Reputation: 1007296
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.
Upvotes: 3