Skip to content

Instantly share code, notes, and snippets.

@luixal
Last active December 16, 2015 17:09
Show Gist options
  • Save luixal/5467911 to your computer and use it in GitHub Desktop.
Save luixal/5467911 to your computer and use it in GitHub Desktop.
Checking for data connection
// Permission needed in Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
// Code:
public boolean isDataConnectionAvailable() {
ConnectivityManager connManager = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connManager.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
private boolean isDataConnectionAvailable() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = connManager.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
// Permission needed in Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
....
// You can registering receiver in Manifest:
<receiver android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
// or register it in code:
this.registerReceiver(this.connectionChangeReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
// Code:
public class ConnectionChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE );
if ( activeNetInfo != null )
{
Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
if( mobNetInfo != null )
{
Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment