0

My app has certain features that are only activated with a network connection is present. I have the code in place to check for a connection, but I'm not sure how I should go about doing constant checks.

I want to check for an active connection in the background once every 2-3 seconds.

...Check for connection ...Wait a few seconds ...Check for connection ...Wait a few seconds ...Check for connection ...Wait a few seconds ...etc

I originally put it in a loop in an IntentService, but I heard you shouldn't run endless loops in IntentServices because they will eventually be terminated. Then read it might be good to use an Alarm but heard from someone else to limit alarms to once per minute or so, otherwise it will cause bad battery drain.

What would be a good way to approach this?

cowsay
  • 1,282
  • 1
  • 15
  • 36
  • This seems like a bad idea. Why not just check for network connectivity when the user tries to use a feature that requires the network. But if you need it, according to [this answer](http://stackoverflow.com/a/3307565/636009) you can [listen for connectivity changes](http://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION). – David Conrad Nov 11 '14 at 18:53
  • "Otherwise it will cause bad battery drain" there's your problem with this, polling constantly in the background will probably drain your battery. Have you looked at simply listening for connectivity changes that are broadcasted by the system? Something like this: http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/ – Nathan Walters Nov 11 '14 at 18:54

1 Answers1

1

BroadcastReciver uses no power and can monitor many facets of the android operating system including connectivity. You can build one into your application manifest or build one with code.

<receiver
        android:name="com.gosyvlester.bestrides.ReceiverWifi"
        android:enabled="false" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

http://developer.android.com/reference/android/content/BroadcastReceiver.html

danny117
  • 5,581
  • 1
  • 26
  • 35