Use a BroadcastReceiver
along with AlarmManager
.
In the method onReceive
of BroadcastReceiver
have the scheduled task executed.
public class ExecutarTarefaProgramadaReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Código a executar
}
}
To start the process use this code:
//Definir a hora de início
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent tarefaIntent = new Intent(context, ExecutarTarefaProgramadaReceiver.class);
PendingIntent tarefaPendingIntent = PendingIntent.getBroadcast(context,1234, tarefaIntent,0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//Definir o alarme para acontecer todos os dias às 10 horas
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, tarefaPendingIntent);
Do not forget to record the BroadcastReceiver
in the Androidmanifest.xml
<receiver android:name="a_sua_package.ExecutarTarefaProgramadaReceiver"/>
See the documentation of Alarmmanager to know how to define other time intervals.
To run 4x per day(every 6 hours), starting at 10 o'clock:
//Definir início para as 10 horas
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
//Definir intervalo de 6 horas
long intervalo = 6*60*60*1000; //6 horas em milissegundos
Intent tarefaIntent = new Intent(context, ExecutarTarefaProgramadaReceiver.class);
PendingIntent tarefaPendingIntent = PendingIntent.getBroadcast(context,1234, tarefaIntent,0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//Definir o alarme para acontecer de 6 em 6 horas a partir das 10 horas
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
intervalo, tarefaPendingIntent);
If the task to execute is time consuming, instead of a Boadccast receiver use a service to run it.
This reply shows a possible implementation.
The code to be executed must be placed in the method onHandleIntent()
.
The implementation handles the device’s status being turned off, re-plotting the task while being turned on.
You have to have a Thread running to see if it’s time and when I’m doing what you want.
– Jorge B.
@Jorgeb. Couldn’t this overload the system if for example I wanted to update a counter every 1s? Let’s say, show a countdown on the notification bar for when it passes 1h to run something. PS: I don’t know the answer, I’m not criticizing you, I just want to know the effects of your solution.
– Math
@Math is how alarms and calendars work. You have no other way of knowing that an hour has passed. It has to be the second.
– Jorge B.
Why create a Thread or a new service if the Android OS has one that natively does this: Alarmmanager
– ramaral