29

I have a Service that is downloading a file from a server. I warn the user to only download the file over Wireless LAN before the download starts.

My problem is that my download gets stuck if I loose the network connection. Is there a way to listen for changes in network connection or if it is lost entirely?

Janusz
  • 187,060
  • 113
  • 301
  • 369

1 Answers1

80

Listen for CONNECTIVITY_ACTION

This looks like good sample code. Here is a snippet:

BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.w("Network Listener", "Network Type Changed");
    }
};

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);        
registerReceiver(networkStateReceiver, filter);
Janusz
  • 187,060
  • 113
  • 301
  • 369
Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • I added a anonymous broadcast receiver just to make the sample totally clear. Thanks for the answer. – Janusz Jul 22 '10 at 10:23
  • What can I do with that networkStateReceiver, and filter objects ??? Please show more detials....! – Zin Win Htet May 27 '14 at 03:31
  • 1
    Don't forget to unregister the receiver when the activity/fragment destroys/pauses – Gil Julio Apr 26 '15 at 10:29
  • 1
    Be careful with the concurrency in the example: even though `startListening()` and `stopListnening()` method are synchronized on their own, **not synchronized to each other**. If two threads are calling the functions independently then there could be a race condition. You need to add a lock object and synchronize to that from both methods. – racs Oct 23 '15 at 00:43