Wait for a network chage in a service, in order to download updates
<p>I have a service which periodically downloads some updates from a web site.
Default period is long, about 10 mins and I do that with an AlarmManager which starts this service.</p>

<p>Network can be on or off, <strong>in case it's off service should download news as soon as network returns on</strong>, because interval is long and, in the worst case, you could have to wait 20 min till next update.</p>

<p>I made a network state broadcast receiver, and, with little code I made a NetworkListener interface:</p>

<pre><code>public interface NetworkStateListener {
public void onNetworkOn();
public void onNetworkDown();
}
</code></pre>

<p>So my service has these 2 methods and <strong>can know when network goes on or off</strong>.</p>

<p>My idea is the following: in the onStart() method I spawn a new thread: if network is off thread waits, otherwise downloads. When onNetworkOn() is called I call a notify():</p>

<pre><code>private boolean threadWaiting; //a flag so that I don't spawn multiple threads
public int onStartCommand(Intent intent, int flags, int startId) {
    if(!threadWaiting){//if already a thread waiting do nothing and exit
        Thread t = new Thread(new Runnable(){

            @Override
            public void run() {
                synchronized(binder){
                    while(!isNetworkOn())
                        try {
                            threadWaiting = true;
                            binder.wait();
                        }catch(InterruptedException ex){
                            ex.printStackTrace();
                        }
                }
                // blocks until network connection is available
               threadWaiting = false;
               //... operations ...
</code></pre>

<p>And this is onNetworkOn() method:</p>

<pre><code>public void onNetworkOn() {
    synchronized(binder){
        binder.notify();
    }
</code></pre>

<p>is this the right way to proceed?</p>
