I have the need to send and take something from a server in Android on every 10 seconds. Here, on StackOverflow, and in the documentation I found literally dozens of ways to implement it (and everything I tried does the job), but it seems that everywhere someone says something is wrong with that way.
I tried with a looping AsyncTask until it is canceled (that is untill the activity is killed), and I found out that it’s not a good solution. Before that I tried with regular Threads, then I found out that it drains the battery a lot.
Now I’ve done it with a Runnable and and the ScheduledExecutorService’s scheduleAtFixedRate function, similar to the code proposed here:
How to run an async task for every x mins in android? . Needless to say, it works. But will it work if my Activity is in the background, for example the user is answering an incoming call?
In the end, I don’t know anymore what is the most proper way of doing it on an Android phone.
Tnx in advance.
Use
Handlerit has various methods likepostDelayed(Runnable r, long delayMillis),postAtTime(Runnable r, Object token, long uptimeMillis)etc.