How to perform a method in a given time?

Asked

Viewed 3,992 times

5

I need that at certain programmed hours, a method is executed even if the user is outside the application.So I searched I will have to use services?
I didn’t quite understand how to program time, I just left the class created here:

public class Notificacao extends Service {


public void onCreate() {

    super.onCreate();

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

    //fez_algo

    Toast.makeText(Notificacao.this, "Fez algo", 1000).show();
    return START_STICKY;

}

But how to execute a method , every 1 hour for example? this method can be declared in the same service class, someone tells me the simplest way?

  • You have to have a Thread running to see if it’s time and when I’m doing what you want.

  • @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 is how alarms and calendars work. You have no other way of knowing that an hour has passed. It has to be the second.

  • 2

    Why create a Thread or a new service if the Android OS has one that natively does this: Alarmmanager

1 answer

6


Use a BroadcastReceiver along with AlarmManager. In the method onReceiveof 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.

  • What good is Broadcastreceiver? I’m asking because I don’t really know, and since I’m interested in the answer I’d like to know a little more in the way indicated by your answer so I can evaluate its pros and cons.

  • 1

    It’s in class ExecutarTarefaProgramadaReceiver, that derives from Broadcastreceiver, where you place the code whatever runs at the time you set it on Alarmmanager. In the example I gave, the Alarmmanager will "instantiate" the class ExecutarTarefaProgramadaReceiver and call the method onReceive every day at 10 o'clock. This happens even if the application, which defined the Broadcastreceiver and began the Alarmmanager, is not running.

  • 1

    The Broadcastreceiver is a class that Android uses to receive Intents. When a Intent Android informs all the "Receivers" registered so that they can process it

  • Hello, it worked thanks a lot. but how do I run 4 x per day?

  • Take a look at the documentation, more specifically the method setRepeating of AlarmManager. And take a look at the note on the behavior of Alarm in Kitkat.

  • I upgraded response code to 4x per day

  • ramaral, thanks Voce is the guy. I just have a doubt, I realized that he’s doing the checking, when I run the application after the scheduled time. If I open the 5:05 app he’s doing the method... it’s either that or there’s something wrong?

  • Yes, that’s right. You should not use the comments to thank. Check this link http://answall.com/help/someone-answers for the correct way to thank you when a reply is helpful.

  • I would also recommend taking a look at Android-Job from Vernote, he does all the heavy work of creating managers, receivers and tauz, and also makes persistent Jobs, running only if certain features are available and tauz. And also treats the different android Apis with their various methods.

  • @ramaral this would be the way to run a method with the APP closed both the screen, and the task list ?

  • 1

    Yes. Broadcastreceveir will be called even when the application is not running.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.