When using Android to connect to the network, it is not always possible to connect to the network. At this time, we 'd betterProgramMake a judgment on the network status when starting. If there is no network, immediately remind the user to set it.
To determine the network status, you must first have the corresponding permissions. The following are the permissions:Code:
That is, access to the network status is allowed:
<Uses-PermissionAndroid: Name= "Android. Permission. access_network_state"> </Uses-Permission>
The following is the judgment code:
Code
Private Boolean Networkstatus (){
Boolean Netsataus = False ;
Connectivitymanager cwjmanager = (Connectivitymanager) getsystemservice (context. connectivity_service );
Cwjmanager. getactivenetworkinfo ();
If (Cwjmanager. getactivenetworkinfo () ! = Null ){
Netsataus = Cwjmanager. getactivenetworkinfo (). isavailable ();
}
If (Netsataus ){
Builder B = New Alertdialog. Builder ( This ). Settitle ( " No available network " )
. Setmessage ( " Set the network? " );
B. setpositivebutton ( " Yes " , New Dialoginterface. onclicklistener (){
Public Void Onclick (dialoginterface dialog, Int Whichbutton ){
Intent mintent = New Intent ( " / " );
Componentname comp = New Componentname (
" Com. Android. Settings " ,
" Com. Android. settings. wirelesssettings " );
Mintent. setcomponent (COMP );
Mintent. setaction ( " Android. Intent. Action. View " );
Startactivityforresult (mintent, 0 ); // If you need to perform the operation again after the setting is complete, you can rewrite the operation code.
}
}). Setneutralbutton ( " No " , New Dialoginterface. onclicklistener (){
Public Void Onclick (dialoginterface dialog, Int Whichbutton ){
Dialog. Cancel ();
}
}). Show ();
}
Return Netsataus;
}
The above code can be used to determine the network status! How can I set the network by myself? I haven't figured it out yet. I'll try again later!