Last active
May 23, 2016 23:20
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//****************************** 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