First step : Receive status information
(1, Write Setactivity method is to get the interface control to set whether to hide
2, this kind inherits broadcastreceiver, the function is to re-broadcast the receiver)
Importandroid.app.Activity;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.net.ConnectivityManager;ImportAndroid.net.NetworkInfo;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast;/*** Created by Administrator on 2014/9/2.*/ Public classConnectionchangereceiverextendsBroadcastreceiver { PublicActivity activity; @Override Public voidOnReceive (Context context, Intent Intent) {BooleanSuccess =false; Connectivitymanager Connectivitymanager=(Connectivitymanager) Context.getsystemservice (context.connectivity_service);//get State ObjectNetworkinfo.state State =Connectivitymanager.getnetworkinfo (Connectivitymanager.type_wifi). GetState (); //determine if a WiFi network is being used if(NetworkInfo.State.CONNECTED = =State ) {TextView View=(TextView) Activity.findviewbyid (r.id.network); View.setvisibility (View.gone); LOG.E ("-------WiFi-----", "connection"); Success=true; } //Get GPRS network connection StatusState =Connectivitymanager.getnetworkinfo (connectivitymanager.type_mobile). GetState (); //determine if the GPRS network is being used if(NetworkInfo.State.CONNECTED = =State ) {TextView View=(TextView) Activity.findviewbyid (r.id.network); View.setvisibility (View.gone); LOG.E ("-------GPRS-----", "connection"); Success=true; } if(!success) {LOG.E ("-------Net-----", "no Connection"); TextView View=(TextView) Activity.findviewbyid (r.id.network); View.setvisibility (view.visible); Toast.maketext (Context,"Network Status Change", Toast.length_long). Show (); } } Public voidsetactivity (activity activity) { This. Activity =activity; }}
Step Two : Create the object and start the broadcast receiver:
New Connectionchangereceiver (this); this. Registerreceiver (receiver,new Intentfilter (connectivitymanager.connectivity_action));
Step three : Add Permissions in manifest:
<android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
The function is to re-connectionchangereceiver the class
Connectivitymanager Connectivitymanager = (connectivitymanager) context.getsystemservice (Context.CONNECTIVITY_ SERVICE);
Ability to get objects.
Fourth Step : Layout file
Default is invisible when initializing displays no network connection reminder, visibility is gone
Fifth Step : Reuse of methods:
Add a change activity method to the broadcast receiver, and do not have a constructor, no error, see
The first step source code.
Android's network status judgment