3

Question


I'm creating a service for my app, but there's probably pritty simple thing I can't realize. Better I say I don't know how to do this probably.

I'd like that my Service refreshs the data every hour if its between 6am and 6pm. How is this possible in a easy way which is also battery-efficient. If you have a some code snippets or a great tutorial for me I would be very happy, because I really like to learn this.

Best Regards

safari

safari
  • 7,565
  • 18
  • 56
  • 82

3 Answers3

2

You can use AlarmManager to start the proceedings. First of all you need to check the current time that is current hour which you can get using Calender.HOUR_OF_DAY. Then you can check the current hour is between 6 to 18. If the condition satisfies you can refresh the data else you can cancel the Alarm and set it to the next period again.

Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
  • next period? the problem is how can I tell my AlarmManger: "hey its now 6-18, reload the data now every hour...." That's where the problems start ... – safari Jan 17 '12 at 11:09
  • by using `Calender.HOUR_OF_DAY` you will get the current hour and you can check the condition by that way. – Lalit Poptani Jan 17 '12 at 11:25
  • so first allways check if its 1 2 3 etc. with Calender.HOUR_OF_DAY, afterwards if that condition is true it checks if the hour is between 6 to 18. Like that it could should work, but how would the code look like. I still don't get how to check if its now 1 2 or 3 etc. – safari Jan 17 '12 at 11:56
  • but how can i loop that, sorry for doublepost... I can get the hour, than I check if its between 6-18o'clock, but how can I loop this???? – safari Jan 17 '12 at 12:41
  • loop is maintained by AlarmManager, you can just have a look at the AlarmManager example. – Lalit Poptani Jan 17 '12 at 12:55
  • first off all the green tick for you, secound a question came up, when i have AlarmManger.setRepeating, it those allways when the criteria of it is allright send an intent? right? if yes i get how to do this now! – safari Jan 17 '12 at 13:13
  • You can create a service and use `PendingIntent.getService()` to work around. – Lalit Poptani Jan 17 '12 at 17:29
1

Create an alarm which when fired refreshes your data and sets a new alarm one our (or 13 hours) in the future depending on current time (past 6pm). See here for more info on the alram manager: http://developer.android.com/reference/android/app/AlarmManager.html

Stefan
  • 4,645
  • 1
  • 19
  • 35
0

you need a broadcast receiver that will fire the intent at 6 am to stop the service and at 6 pm to again start the service. By this way you can also improve battery consumtion.

Anil
  • 153
  • 1
  • 6
  • the problem is, i have a reload button in my app, so the service has to run all the time, that he can reload the data. – safari Jan 17 '12 at 11:14