A commonly used network help class, commonly used network
1. Background
When developing a network, you always need to judge the Network frequently. For example, is there a network? Is the mobile phone network or wifi connected? Whether the proxy network is used or not. Based on the principle of no re-writing code, we usually strip this code out and create a separate file.
2. Code display
Import android. content. contentResolver; import android. content. context; import android. database. cursor; import android.net. connectivityManager; import android.net. networkInfo; import android.net. uri; public class NetUtil {/*** check whether the user's network exists */public static boolean checkNet (Context context) {// judge: WIFI connection boolean isWIFI = isWIFIConnection (context); // judgment: Mobile connection boolean isMOBILE = isMOBILEConnection (context ); // If Mobile is connected, determine which APN is selected if (isMOBILE) {// whether the APN is selected and whether the agent information has content, if there is a wap readAPN (context); // you can determine which APN is selected} if (! IsWIFI &&! IsMOBILE) {return false;} return true;}/*** check whether the agent information of the APN has been selected, if there is a wap method ** @ param context */private static void readAPN (Context context) {Uri PREFERRED_APN_URI = Uri. parse ("content: // telephony/carriers/preferapn"); // The 4.0 simulator shields this permission. // The operation contact is similar to ContentResolver resolver = context. getContentResolver (); // determines which APN has been selected as Cursor cursor = resolver. query (PREFERRED_APN_URI, null, null); if (cursor! = Null & cursor. moveToFirst () {GlobalParams. PROXY = cursor. getString (cursor. getColumnIndex ("proxy"); GlobalParams. PORT = cursor. getInt (cursor. getColumnIndex ("port");}/*** judgment: Mobile link ** @ param context * @ return */private static boolean isMOBILEConnection (Context context) {ConnectivityManager manager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo networkInfo = Manager. getNetworkInfo (ConnectivityManager. TYPE_MOBILE); if (networkInfo! = Null) {return networkInfo. isConnected ();} return false;}/*** judgment: WIFI Link ** @ param context * @ return */private static boolean isWIFIConnection (Context context) {ConnectivityManager manager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager. getNetworkInfo (ConnectivityManager. TYPE_WIFI); if (networkInfo! = Null) {return networkInfo. isConnected () ;}return false ;}}
3. Summary
The above shows whether there is a network connection, whether it is a mobile phone connection, or whether it is an APN connection.