Skip to content

Instantly share code, notes, and snippets.

@amilcar-sr
Last active May 23, 2016 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amilcar-sr/dc807488058c4eefe53871750cef100c to your computer and use it in GitHub Desktop.
Save amilcar-sr/dc807488058c4eefe53871750cef100c to your computer and use it in GitHub Desktop.
BroadcastReceiver implementation to make your android app aware of internet connection changes.
//****************************** Class ******************************
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* BroadcastReceiver that listens for internet connection changes and notifies these changes
* to the subscribers for ConnectionRestoredEvent and ConnectionLostEvent.
* @see <a href="https://github.com/greenrobot/EventBus"</a> for further information about EventBus.
*/
public class ConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (isNetworkAvailable(context)) {
EventBus.getDefault().post(new ConnectionRestoredEvent() /* Event you have to create and handle */);
} else {
EventBus.getDefault().post(new ConnectionLostEvent() /* Event you have to create and handle */);
}
}
/**
* Verifies whether the device has internet connection or not.
*
* @param context Context
* @return true if connected, false otherwise.
*/
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
//****************************** IMPORTANT! ADD THIS INTO YOUR MANIFEST (inside the <application> tag) ******************************
<receiver android:name="{your app package}.receivers.ConnectionReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment