Android: execute code in regular intervals
You can do that using the below code,
Hope it helps!
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
try{
//do your code here
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed(this, 1000);
}
}
};
//runnable must be execute once
handler.post(runnable);
Android - how to run a piece of code every minute (synced with the device time)
You can use this code:
Thread thread = new Thread(new Runnable()
{
int lastMinute;
int currentMinute;
@Override
public void run()
{
lastMinute = currentMinute;
while (true)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
currentMinute = calendar.get(Calendar.MINUTE);
if (currentMinute != lastMinute){
lastMinute = currentMinute;
Log.v("LOG", "your code here");
}
}
}
});
thread.run();
Call Android Service at regular intervals [GoodApporach?]
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);
Call Particular Method after regular interval of time
You can use Timer for the fixed-period execution of a method.
Here is a sample of code:
final long period = 0;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// do your task here
}
}, 0, period);
How to run a method every X seconds
The solution you will use really depends on how long you need to wait between each execution of your function.
If you are waiting for longer than 10 minutes, I would suggest using AlarmManager
.
// Some time when you want to run
Date when = new Date(System.currentTimeMillis());
try {
Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched
// Note: this could be getActivity if you want to launch an activity
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0, // id (optional)
someIntent, // intent to launch
PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
);
AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE
);
alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent
);
} catch(Exception e) {
e.printStackTrace();
}
Once you have broadcasted the above Intent
, you can receive your Intent
by implementing a BroadcastReceiver
. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter);
method. For more information on BroadcastReceiver
's please refer to the official documentation..
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("MyReceiver: here!") // Do your work here
}
}
If you are waiting for shorter than 10 minutes then I would suggest using a Handler
.
final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
System.out.println("myHandler: here!"); // Do your work here
handler.postDelayed(this, delay);
}
}, delay);
How to run some task at specified time interval in android using AlarmManager?
Set AlarmManager like this:
private static final int REPEAT_TIME_IN_SECONDS = 60; //repeat every 60 seconds
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
REPEAT_TIME_IN_SECONDS * 1000, pendingIntent);
Change AlarmManager.RTC
to AlarmManager.RTC_WAKEUP
if u want to wake up phone when it
goes off. More about AlarmManager here
Those two parameters also means that your alarm time will be System.currentTimeMilis()
which is time in UTC.
EDIT :
Your solution using AlarmManager.ELAPSED_REALTIME
which measure time since device boot including sleep. It means that if you want run this code after 10 seconds and then want to repeat it and your device is running for more than that, PendingIntent will be triggered immediately because 10 seconds after boot occurs in the past.
EDIT 2 :
If u want to run code just once after 10 seconds try this:
private static final int START_AFTER_SECONDS = 10;
...
if (radioBtnChecked)
{
Runnable mRunnable;
Handler mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
Intent serviceIntent = new Intent(MyActivity.this, MyService.class);
MyActivity.this.startService(serviceIntent);
}
};
mHandler.postDelayed(mRunnable, START_AFTER_SECONDS * 1000);
}
Running tasks at regular intervals in android
The Service will pause its execution when the device goes to sleep. There's no way around that. The only two solutions are the ones you mentioned in the updates, namely a WakeLock
and the AlarmManager
.
The AlarmManager
will be the preferred solution to avoid battery drain. If you need to perform a task at different intervals, you may use setInexactRepeating()
. You can set one alarm for each task you need to perform.
You will still need to add a wakelock for the time it takes to finish the job, as the alarm will wake the device but it will not keep it awake for long. For an implementation of that, check CommonsWare's example code here: https://github.com/commonsguy/cwac-wakeful
calling a function in android after intervals?
Use CountDownTimer
CountDownTimer t = new CountDownTimer( Long.MAX_VALUE , 10000) {
// This is called every interval. (Every 10 seconds in this example)
public void onTick(long millisUntilFinished) {
Log.d("test","Timer tick");
}
public void onFinish() {
Log.d("test","Timer last tick");
start();
}
}.start();
how can I call function every 10 sec?
Do it like this:
final Handler ha=new Handler();
ha.postDelayed(new Runnable() {
@Override
public void run() {
//call function
ha.postDelayed(this, 10000);
}
}, 10000);
Related Topics
Check If a Vpn Connection Is Active in Android
How to Add The Icon for Swipeable Tabs
Android - How to Get View from Context
Why Is Fusedlocationapi.Getlastlocation Null
How to Make The Navigation Bar Transparent
Play Store Having New Version of The App, But Not Showing Update
How to Get Total Ram Size of a Device
How to Forward My Localhost Ip-Address to an Android Emulator
Android: Wait on User Input from Dialog
How to Make a Linearlayout Scrollable
Android Httpsurlconnection Eofexception
Install_Failed_Cpu_Abi_Incompatible on Device Using Intellij
Firebase Android Onauthstatechanged Called Twice
How to Get Background Color from Current Theme Programmatically
How to Show Alphabetical Letters on Side of Android Listview
Unfortunately App Is Getting Stopped While Checking for Network
How to Print a Double with Two Decimals in Android
How to Add Radio Button Dynamically as Per The Given Number of Counts