1. Background Introduction
When doing the development of the network, always have to judge the network, for example, whether there is a network? Are you connected to a mobile network or WiFi? Whether to go to the agent network and so on information. Based on the principle of non-repetitive write code, we typically peel out such code and make 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 the user's network: whether there is a network */public static Boolean checknet (context context) {//judgment: WiFi link Boolean iswifi = iswificonnection (context) ;//Judgment: Mobile link Boolean ismobile = ismobileconnection (context);//If mobile is in the link, determine which APN is selected if (ismobile) {//APN is selected, Agent information whether there is content, if there is a WAP mode READAPN (context);//Determine which APN is selected}if (!iswifi &&!ismobile) {return false;} return true;} /** * APN is selected, whether the agent information has content, if there is a WAP way * * @param context */private static void Readapn (context context) {Uri Preferred_apn_uri = Uri.parse ("CONTENT://TELEPHONY/CARRIERS/PREFERAPN");//4.0 simulator screen out this permission//action contact like Contentresolver resolver = Context.getcontentresolver ();//Determine which APN is selected by cursor cursor = resolver.query (Preferred_apn_uri, NULL, 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) {Connectivity Manager 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) {Connectivitymana GER 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 main shows: whether there is an Internet connection, whether it is a mobile phone connection, whether it is an APN connection.
A common network helper class