Reputation: 336
I developed an app that does something every X time set. I thought about few ideas how to do that but i learn java and android mySelf and i don't know what is the right method to do that . So, my app runs as a "Service" and i created a While loop that has a if Statement like:
Example = "mySetTim = 6/7/14;"
while(true){
if(currentDate == getTime){
//Do Something....
}
}
and it works, but if i want to do "something" every day. How can i pass it because my SetTime date is not return 2 times in a year .
Upvotes: 2
Views: 1129
Reputation: 448
You are in the right path, a service is the best method I know to achieve what you are trying to do, here's an example to help you use a service correctly (avoid the while loop)
public class Bg_Service extends Service {
private Timer timer=new Timer();
private long UPDATE_INTERVAL = 10000; //in Milliseconds, in your case every 24h
private static long DELAY_INTERVAL = 0; //how much time your service needs to wait before starting the process
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate()
{
super.onCreate();
_startService();
}
private void _startService()
{
timer= new Timer();
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
//Do something
}
},
DELAY_INTERVAL,
UPDATE_INTERVAL);
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
}
Upvotes: 0
Reputation: 5867
You should use the Alarm API for the job.
See a prior post on that matter exactly;
Any other solution which relies e.g. on keeping a service in the air and monitoring intervals until action will break when Android will experience low resources and take your service down.
Note that if you want your logic to continue after device restart you will need to restart the alarm after boot. Read here for details.
Good luck
Upvotes: 0
Reputation: 8338
What you are looking for is a Task Scheduler: http://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html
There are many ways to control regular calls in Java. You could use Thread.sleep(X) if your application doesn't have a background job to do or, if you have a task interspersed on other calls you could just check if the time has passed, something like:
long somtimefromnow = System.currentTimeMillis() + 12312323;
Then your code would do periodic checks:
if (System.currentTimeMillis() > somtimefromnow) { doSomething(); }
BUT DO NOT check if the time is ==
as you are doing. It is not guaranteed the exact time will be compared.
Upvotes: 1