Skip to content

Instantly share code, notes, and snippets.

@Tikitoo
Last active October 31, 2018 06:11
Show Gist options
  • Save Tikitoo/384bc47db18c2c37f8a4 to your computer and use it in GitHub Desktop.
Save Tikitoo/384bc47db18c2c37f8a4 to your computer and use it in GitHub Desktop.
Android check network available
<manifest>
<!-- other code -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// ... other code
boolean flag = NetworkUtils.getInstance(this).isNetworkAvailable();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public class NetworkUtils {
private static Context mCtx;
private static NetworkUtils mInstance;
public NetworkUtils(Context context) {
this.mCtx = context;
}
public static NetworkUtils getInstance(Context context) {
if (mInstance == null) {
mInstance = new NetworkUtils(context.getApplicationContext());
}
return mInstance;
}
public static boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment