Connectivitymanager
Connectivitymanager as an Android network connection management class, the main functions are as follows:
1. Notify the application of changes in network status, send broadcast action:connectivity_action
2. Connection management of WIFI,GPRS and other networks (availability, connection status, etc.)
3. Provides an API for applications to request or select a network for data transfer
Required Permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Networkactivity
Public class networkactivity extends actionbaractivity { Private Final StaticString TAG ="RAISE";@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (r.layout.activity_net_work); Check_network (); Intentfilter filter =NewIntentfilter (connectivitymanager.connectivity_action); Registerreceiver (networkreceiver, filter); }Private void check_network() {//Get Network management classConnectivitymanager manager = (Connectivitymanager) getsystemservice (Context.connectivity_service);//Get the network currently availableNetworkinfo activenetworkinfo = Manager.getactivenetworkinfo ();//Determine the current network type if(Activenetworkinfo! =NULL) {if(Activenetworkinfo.gettype () = = Connectivitymanager.type_mobile) {LOG.D (TAG,"Current network:"+ Activenetworkinfo.gettypename ()); }Else if(Activenetworkinfo.gettype () = = Connectivitymanager.type_wifi) {LOG.D (TAG,"Current network:"+ Activenetworkinfo.gettypename ()); } networkinfo.state state = Activenetworkinfo.getstate ();if(State.ordinal () ==networkinfo.state.connected.ordinal ()) {LOG.D (TAG, activenetworkinfo.gettypename () +"Network Available"); } }Else{LOG.D (TAG,"No Network Available"); }} broadcastreceiver Networkreceiver =NewBroadcastreceiver () {@Override Public void OnReceive(context context, Intent Intent) {if(Intent.getaction (). Equals (Connectivitymanager.connectivity_action)) {LOG.D (TAG,"Broadcast Acceptance"); Check_network (); } } };@Override protected void OnDestroy() {unregisterreceiver (networkreceiver);Super. OnDestroy (); }}
It has been tested that the broadcast will be called once after registration.
This broadcast will only be invoked if the current network is switched to another network (Internet access is required) or no network.
:
Of course, you can also get mobile and WiFi Networkinfo separately to handle
NetworkInfo mobile_networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifi_networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mobile_networkInfo.isConnected()){ //... }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android_connectivitymanager Connection Management