In my app, I would like to offer an action, which shall be executed in background regularly. So I use the AlarmManager, which starts an IntentService.
The tricky part is, that this background action needs Internet connection. So I tried using a WakeLock which didn’t seem to enforce a connection, when the device was locked.
Then I thought about registering a BroadcastReceiver to listen for “android.net.conn.CONNECTIVITY_CHANGE” when the service starts and immediately unregistering it, as soon as the desired broadcast is received.
My code looks something like this:
public class BackgroundService extends IntentService {
private static final IntentFilter filter =
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
private static NetworkStateChangedReceiver receiver =
new NetworkStateChangedReceiver();
protected void onHandleIntent(Intent intent) {
registerReceiver(receiver, filter);
}
}
My question is now: Will this receiver be destroyed, as soon as the service stops (as it has nothing to do, as long as no connection is available)?
And therefore, how can I realize a service, that delays it’s work until a network connection is availalbe?
Thanks.
Yes. It will live for a few microseconds.
Use
ConnectivityManagerandgetActiveNetworkInfo(), see if there’s a connection, and if not, just exitonHandleIntent()and wait for the next alarm.Or, register your
CONNECTIVITY_ACTIONreceiver in the manifest and use it to schedule and cancel your alarms, so the alarms are only active while there’s a connection.There are various other strategies, but those two should give you a starting point.