3

I need to call the speak method every 5 minutes, then i want to run in background the async method called callspeak, that calls back the speak method(a public method of a different class). It has to loop every 5 minutes

    class callSpeak extends AsyncTask<String, Void, String> {
    activityAudio a = new activityAudio();
    @Override
    protected String doInBackground(String... strings) {

        try
        {
         while (true){
               a.speak();
                Thread.sleep(300000);
            }
        }
        catch (InterruptedException e)
        {e.getMessage();}
      return null;
    }

}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • In this case I would use a Handler calling a postDelayed function with your desired interval on it, check this thread, you can find a good code example: https://stackoverflow.com/questions/6207362/how-to-run-an-async-task-for-every-x-mins-in-android – Luis Pascual Mar 14 '20 at 11:57

3 Answers3

5

If you want to run the method only when the app is open, you can simply use TimerTask.

Timer myTimer = new Timer ();
TimerTask myTask = new TimerTask () {
    @Override
    public void run () {
        // your code 
        callSpeak().execute() // Your method
    }
};

myTimer.scheduleAtFixedRate(myTask , 0l, 5 * (60*1000)); // Runs every 5 mins

If you want to run it in background even if app is not running, you can use AlarmManager and repeat the task every 5 mins.

Hope it helps

Susheel Karam
  • 837
  • 7
  • 16
  • You can follow this codelab - https://codelabs.developers.google.com/codelabs/android-training-alarm-manager/index.html . May I know why you want to run it in background? – Susheel Karam Mar 14 '20 at 12:53
  • I solved my problems, thank you so much. but I have another question for you. How Can I make dynamic the time needed to call the function back? For example now the function is called back every 5min. I would like to have this time randomly changable every time the function is called back. –  Mar 14 '20 at 13:03
0

You can do like this:

Handler mHandler = new Handler();

Runnable mRunnableTask = new Runnable()
{
     @Override 
     public void run() {
          doSomething();
          // this will repeat this task again at specified time interval
          mHandler.postDelayed(this, yourDesiredInterval);
     }
};

// Call this to start the task first time
mHandler.postDelayed(mRunnableTask, yourDesiredInterval);

Don't forget to remove the callbacks from handler when you no longer need it.

DB377
  • 403
  • 4
  • 11
0

The latest and the most efficient way to perform this, even if you come out of the activitiy or close the app is to implement the WorkManager from the AndroidX Architecture.

You can find more details here from the official documentation: Schedule tasks with WorkManager

Mohammed Mukhtar
  • 1,731
  • 20
  • 18