Android Timer or Service


Hello with all I have an application that works with a database, I want to execute a query in the base like the one that I leave later, the detail is that this method (query) should only be executed at 7:30 of the Tomorrow every day someone can help me with this problem.

Thank you in advance for the help

public void borrarRegistros(){
    String consulta="delete from registros"; //borrar todos los registros de la tabla registros
    try {
        Cursor c=MainActivity.adapter.get_sqliteDB().rawQuery(consulta,null);
    }catch (Exception ex){
asked by Kevtho 22.10.2016 в 07:02

1 answer


The ideal for your case is neither, at least the service is not directly. You need to use the AlarmManager , which ensures you "wake up" your application, even if it is not running, and using a intent , shoot the action or query you need! More info here " Recurring Alarms ". The alarm service can wake up a service and make the query in the background.

Example of use:

private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, QueryService.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

// Poner alarma para comenzar a las 7:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 7);
calendar.set(Calendar.MINUTE, 30);

// setRepeating() permite definir el intervalo de repetición
long unDia = 1000 * 60 * 60 * 24;
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
    unDia, alarmIntent);
answered by 23.10.2016 / 20:13