Last active
October 31, 2018 06:11
-
-
Save Tikitoo/384bc47db18c2c37f8a4 to your computer and use it in GitHub Desktop.
Android check network available
This file contains hidden or 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
<manifest> | |
<!-- other code --> | |
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> | |
</manifest> |
This file contains hidden or 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
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
// ... other code | |
boolean flag = NetworkUtils.getInstance(this).isNetworkAvailable(); | |
} | |
} |
This file contains hidden or 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
private boolean isNetworkAvailable() { | |
ConnectivityManager connectivityManager | |
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); | |
return activeNetworkInfo != null && activeNetworkInfo.isConnected(); | |
} |
This file contains hidden or 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
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