Service question - how do I make a service run periodically?

General topics about the Android-Platform itself.
Coding issues please to the subforum right below.

Service question - how do I make a service run periodically?

Postby Sweevo » Tue Nov 04, 2008 1:44 pm

Let's say I have an app that logs your route and lets you see it and post it online...

When the phone boots, it should run for a fraction of a second, putting your location in a database, and maybe every 15-20 minutes after that (don't want to bother other apps too much!), whether the app is launched or not.

Do I just use a service that starts at boot time, and have its thread sleep for 20 minutes, work for 1 second, and repeat? Or is there some clever scheduler I missed? Either way, what's a good example for getting started?

Note: I don't think the rest of the app (the activity component) needs to communicate with the service directly, since it can just read the data from the database.
Sweevo
Developer
Developer
 
Posts: 35
Joined: Thu Oct 16, 2008 9:27 am

Top

Postby MrSnowflake » Tue Nov 04, 2008 2:39 pm

For the AutoStarting service there's a thread about that.

Then you just make a service which does:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. /** in MyService.java */
  2.  
  3. private Handler mHandler;
  4.  
  5. private final int DELAY = 360*1000*20; // 20min in ms
  6.  
  7. public void onCreate(){
  8.  
  9.   mHandler = new Handler();
  10.  
  11.   mHandler.postDelayed(updateRunnable, DELAY);
  12.  
  13. }
  14.  
  15.  
  16.  
  17. private Runnable updateRunnable = new Runnable() {
  18.  
  19.   public void run() {
  20.  
  21.     // setup gps stuff
  22.  
  23.     // do the update
  24.  
  25.     // remove gps stuff (save battery!!!)
  26.  
  27.     MyService.this.mHandler.postDelayed(this, DELAY);
  28.  
  29.   }
  30.  
  31. };
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
That should do it.

the // do the update would probably be something like:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. while(!updated)
  2.  
  3.   sleep(1000); // with the apropriate try stuff
Parsed in 0.031 seconds, using GeSHi 1.0.8.4
Where updated is a boolean which will be flagged when the LocatonChangedListener (or what's it's name) is invoked.
User avatar
MrSnowflake
Moderator
Moderator
 
Posts: 1439
Joined: Sat Feb 16, 2008 3:11 pm
Location: Flanders, Belgium

Postby Sweevo » Tue Nov 04, 2008 7:57 pm

Thanks. That's exactly what I've been looking for!

There's so much you can do with this - alert you when friends are nearby, using your route to draw using the earth as a canvas (if you change it to every 2-5 minutes, probably)...
Sweevo
Developer
Developer
 
Posts: 35
Joined: Thu Oct 16, 2008 9:27 am

Top

Return to General

Who is online

Users browsing this forum: No registered users and 3 guests