Scheduling recurring task in Android
I am not sure but as per my knowledge I share my views. I always accept best answer if I am wrong .
Alarm Manager
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. This means that the phone will in some cases sleep as soon as your onReceive()
method completes. If your alarm receiver called Context.startService()
, it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver
and Service
will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.
Note: 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.
Timer
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
\\ here your todo;
}
}, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));
Timer
has some drawbacks that are solved by ScheduledThreadPoolExecutor
. So it's not the best choice
ScheduledThreadPoolExecutor.
You can use java.util.Timer
or ScheduledThreadPoolExecutor
(preferred) to schedule an action to occur at regular intervals on a background thread.
Here is a sample using the latter:
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
// call service
}
}, 0, 10, TimeUnit.MINUTES);
So I preferred ScheduledExecutorService
But Also think about that if the updates will occur while your application is running, you can use a Timer
, as suggested in other answers, or the newer ScheduledThreadPoolExecutor
.
If your application will update even when it is not running, you should go with the AlarmManager
.
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.
Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.
Android: Scheduling a repeating task for short time intervals isn't working
What you need is a Service and a CountDownTimer.
Start a service and initialize the count down timer for 10 to 15 minutes as you would prefer when the timer finishes you reinitialize the same timer and show notification in onFinish method of the timer.
This way you will be showing notifications even when the app is closed.
how to schedule a task on android
The AlarmManager class enables the scheduling of repeated alarms that
will run at set points in the future. The AlarmManager is given a
PendingIntent to fire whenever an alarm is scheduled. When an alarm is
triggered, the registered Intent is broadcast by the Android system,
starting the target application if it’s not already running.
Create a class that inherits from BroadcastReceiver. In the onReceive method, which is called when the BroadcastReceiver is receiving an Intent broadcast, we will set up the code that runs our task.
AlarmReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// For our recurring task, we'll just display a message
Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();
}
}
We then need to register the BroadcastReceiver in the manifest file. Declare the AlarmReceiver in the manifest file.
<application>
.
.
<receiver android:name=".AlarmReceiver"></receiver>
.
.
</application>
In your calling Activity include the following instance variables.
private PendingIntent pendingIntent;
private AlarmManager manager;
In onCreate() we create an Intent that references our broadcast receiver class and uses it in our PendingIntent.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Retrieve a PendingIntent that will perform a broadcast
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
}
We then include the method that will set up the recurring alarms. Once set, the alarm will fire after every X time, here we are taking 10 seconds example you can simply calculate this in order to trigger it for every day.
public void startAlarm(View view) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 10000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
Next, we’ll also set up the cancelAlarm() method to stop the alarms, if needed.
public void cancelAlarm(View view) {
if (manager != null) {
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
}
Related Topics
Android Marshmallow Request Permission
Creating a System Overlay Window (Always on Top)
How to Get Extra Data from Intent on Android
Libraries Do Not Get Added to Apk Anymore After Upgrade to Adt 22
Retrieve a Fragment from a Viewpager
Install Application Programmatically on Android
Difference Between Gravity and Layout_Gravity in Android
How to Save Users Score in Firebase and Retrieve It in Real-Time in Android Studio
Picasso V/S Imageloader V/S Fresco VS Glide VS Coil
How to Build a Horizontal Listview With Recyclerview
Scrollview Vertical and Horizontal in Android
How to Detect When Wifi Connection Has Been Established in Android