Android Polling from a Server periodically
Asked Answered
J

4

6

I want to pull some data from a server every x minutes. IF the info contains certain information I would like to create a notification. I want this polling to happen even when the app is in the background, or the phone is asleep. I have a few questions about polling in android.

  • What is the best way to go about doing it? Should I use an
    IntentService, an AlarmManager, something else?

  • How often should I be polling the data? I would like to keep it relatively often, say under every 10 minutes.

Jubbah answered 2/8, 2012 at 14:4 Comment(0)
D
12

I would favour an AlarmManager as I try not to run continuously running services unless I really need to but it does really depend on how you will be using it.

If it were me I would (based on the limited description) :-

  1. Set up an AlarmManager to fire in say 10 minutes.
  2. In response to the alarm, start a service that polls the data.
  3. After polling it should set itself up with a new Alarm to fire again in another 10 minutes.
  4. The service shuts itself down.
Dorr answered 2/8, 2012 at 14:20 Comment(4)
This sounds like a great solution, I will try it out. So would calling the alarmservice say every 2 minutes put to much strain on the phone's battery life?Jubbah
The AlarmManager wouldnt but your polling code most likely would. It will keep the device constantly awake.Dorr
Also, if I set up the AlarmManager to go off every 10 minutes or so, couldn't I just do the polling within the AlarmManager instead of starting a service?Jubbah
The alarmmanager only fires an intent at the specified time. You would then handle the intent whatever way was best for your situation. A service makes sense as there is no UI and is less likely to be killed by the OS.Dorr
N
1

You'll want to use something like Cloud to Device Messaging (C2DM) (aka push notifications in the iPhone world)

A great tutorial can be found at http://blog.mediarain.com/2011/03/simple-google-android-c2dm-tutorial-push-notifications-for-android

Nectarous answered 2/8, 2012 at 14:17 Comment(2)
Unfortunately I am using android 2.1 and this requires 2.2 +Jubbah
in August 2012 still using Android 2.1? I suggest move on to 2.2+ or even 2.3(.3)+.. check the Android platform versions in percents: developer.android.com/about/dashboards/index.htmlMateya
C
0

You could use Handler to listen the server. For example please check Run code over and over

Compendious answered 2/8, 2012 at 14:10 Comment(0)
I
-5

You could create a thread that does this. In your run method you could create a loop that polls the server every 10 minutes.

Irremeable answered 2/8, 2012 at 14:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.