Use BroadcastReceiver
together with AlarmManager
.
In the onReceive
of BroadcastReceiver
method, have the scheduled task run.
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 register BroadcastReceiver
in AndroidManifest.xml
<receiver android:name="a_sua_package.ExecutarTarefaProgramadaReceiver"/>
See the AlarmManager documentation for how to set other time slots.
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 be run is time-consuming, instead of a Boadccast receiver, use a service to run it.
This response shows a possible implementation.
The code to be executed should be placed in the onHandleIntent()
method.
The implementation handles the status of the device being turned off, rescanning the task again when it is turned on.