Perform database actions in the background every 10 minutes - android

I want to perform database actions in the background every 10 minutes. What is the best method?
Maybe:
Threads: how?
Services: very complicated?
AsyncTasks: too long period
My current approach:
CountDownTimer clearDBsCountDownTimer = new CountDownTimer(600000, 600000) {
#Override
public void onFinish() {
ClearDBs();
}
};
private void ClearDBs() {
// Clearing databases here
clearDBsCountDownTimer.start();
}
But it's not working: I think because the ClearDBs() method waits for the CountDownTimer to finish, right?
But how to do that correctly: any ideas?

AlarmManager + IntentService is the cleanest approach.
With AlarmManager you can schedule periodic IntentServices.
An IntentService is a service that performs a specific action in a background thread (onHandleIntent() call) and dies.
They make a perfect mix to perform periodic jobs in background.
Check for example this post.
Please be careful with this kind of operations since they could result in draining the battery (and having angry users).
As suggested by #Squonk you can use setRepeating(...) or setInexactRepeating(...) to schedule periodic events.
If you want to perform this background task only when your app is in foreground, you can still cancel the event calling manager.cancel()

Creating a bound service would be a good idea.
And for threading use ScheduledExecutorService

Related

Firing off an Intent Service every X seconds, whats the difference in performance?

I know there are many ways to call a function every x seconds or schedule a job. My question is what is the best fit solution for my problem?
I have a heavy task that I want to run in a background thread (Database queries, making HTTP calls).
For this I use an IntentService since it's onHandleIntent function runs in a background worker thread and the started services are queued.
The queue doesn't really matter for me since startService() will only be called from one place.
Now, I want to start this service frequently, sometehing like 10-15 seconds.
This was my old solution:
class MyService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
mutex = new Object();
while(isServiceRunning) {
doTheBigJob();
syncrhonized (mutex) {
mutex.wait(15000);
}
}
}
}
I assume this is bad practice.
Now my Intent service only contains doTheBigJob(). But how should I time my startService() call to make this happen every 15 sec for forever. What is the most optimal way?
This is a KIOSK app so it will always be in the foreground and the user can't escape it.

Is it a good practice to use TimerTask in OnHandleIntent in IntentService?

i have an IntentService that calls webservice in OnHandleIntent every 45 seconds using TimerTask.
my question is:
i am calling on app start the IntentService, and in OnHandleIntent the task keeps repeating due to TimerTask..is it a good practice to do this or does this have any drawbacks? should i use an alarm manager in my activity to call the intent service every amount of time or its fine to keep on repeaing the task in OnHandleIntent using the timer task?
my code is like this:
#Override
protected void onHandleIntent(Intent intent)
{
context=this; //INTENT CONTEXT
final int timerValue = Integer.parseInt(MainActivitySharedPref.GetValue(context, "serviceTimer"));
Log.d(TAG, "DOWNLOADSERVICE called having MainActivity.callService as: " + MainActivity.callService);
t = new Timer();
task = new TimerTask()
{
public void run() {
//run tasks
};
t.scheduleAtFixedRate(task, 0, timerValue); // service executes task every 45 seconds
Thank you.
Is it a good practice to use TimerTask in OnHandleIntent in IntentService?
Absolutely not.
IntentService is designed to allow you to perform work in a supplied background thread via onHandleIntent(). It is not designed for you to fork threads, register listeners, set up TimerTask/ScheduledExecutorService, or do anything else that would be running past the end of onHandleIntent(). The IntentService will shut itself down once onHandleIntent() ends, after which Android may terminate your process within seconds, before your background threads (or, in this case, TimerTask) can do its work.
Please use a regular Service.
should i use an alarm manager in my activity to call the intent service every amount of time or its fine to keep on repeaing the task in OnHandleIntent using the timer task?
If you are doing this only while some activity of yours is in the foreground, the every-45-seconds part is OK. If you are trying to do this continuously, on battery-powered devices, be prepared to be attacked by users for the battery drain that you are causing.
But, while an activity of yours is in the foreground... ScheduledExecutorService (the modern replacement for TimerTask) in a regular Service should be fine. You should not need AlarmManager, which is specifically designed to give you control after your process has been terminated, for longer polling periods.

Call Android Service at regular intervals [GoodApporach?]

My Requirement is
Android application has to send user location details(latitude & longitude) to the server for every one hour(which is configurable).
The approach I followed is using the alarm manager i am invoking my service at configured intervals which will send the location details to server irrespective of whether the application is running.
Is this a good approach?
I prefer ScheduledExecutorService, because it is easier for background Tasks.
AlarmManager:
The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock.
ScheduledThreadPoolExecutor:
You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action to occur at regular intervals on a background thread.
You can see complete answer here => Which is Better ScheduledExecutorService or AlarmManager in android? And Here
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Hit WebService
}
}, 0, 1, TimeUnit.HOURS);
Yes, using AlarmManager is a good approach
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
please refer this https://developer.android.com/training/scheduling/alarms.html
Android service run on UI thread so you should not execute long running task in it, like sending data to server. The approach you can use is ScheduledThreadPoolExecutor or AlarmManager for scheduling and using asynctask or any other background thread for sending data to servers
I prefer Timer for repeated tasks.
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
process();
}
};
Timer mTimer = new Timer();
mTimer.schedule(timerTask, 0,60*60*60*1000);

How to make periodic rest requests from Activity?

One of my activity periodically updates nearby friends, which location is obtained from rest service
Currently I use postDelay:
private Runnable updateNearbyFriendsTask = new Runnable() {
#Override
public void run() {
list = api.getNearby(.....)
handler.postDelayed(this, UPDATE_RATE);
}
};
The problem is that postDelayed executed on UI thread, so this runnable task block ui with poor internet connection.
What is the right way to make periodic background rest requests from activity? I don't want to create service for that, because this rest method is used only in this activity.
EDIT
Currently switched to using ScheduledExecutor
this.scheduledExecutor.scheduleWithFixedDelay(new UpdateNearbyFriendsTask(), 0, UPDATE_RATE, TimeUnit.MILLISECONDS);
private class UpdateNearbyFriendsTask implements Runnable() {
#Override
public void run() {
list = api.getNearby(.....)
runOnUiThread(.....)
}
};
I don't see what the problem is with creating a Service, even if it is only used for this activity.
That being said, have a look at the TimerTask. It seems to do what you want.
How about BroadCast receiver using Alarm manager.. http://developer.android.com/reference/android/app/AlarmManager.html
Since its a long running and on going task, would you want to write a Service or an Intent service which does the background job for you.
You can just ping the service whenever your time ticks and let the service do the network activity, freeing up the UI thread for something else. you can always query the service to know the status, or the service itself can respond back to your UI thread.
For ticking the timer, you can use the alarm manager, or perhaps something else (I am not good at any :P )

Call a specific action in certain time in Android

What I want is 5 minutes after I open the application do a specific work.
I am not sure what I suppose to do.Should I create an AsyncTask in onCreate method of my main activity or a thread? Or should i do something completely different?
This may help: http://developer.android.com/reference/android/app/AlarmManager.html
Your question is a combined question asking how (way) to perform a task as well as how to schedule it.
Decide what is the task you want to perform. If its a long running task, use either AsyncTask or IntentService
To schedule the task you can either use Hander postDelayed, Timer or AlarmManager. My pref. would be a one-time AlarmManager - Once registered, even if you app is not running, the callback will be triggered.
You could use a Handler :
new Handler().postDelayed(new Runnable() { public void run() {
//your delayed action here, on UI Thread if needed
}
}, 1000 * 60 * 5 );
Regards,
Stéphane

Categories

Resources