To develop a network-based application on the Android platform, you must determine the current network connection status. The following code, as an example, describes in detail how to judge the current network situation.
First, let's look at a self-defined application class.
Public class networkdetector {</P> <p> Public static Boolean detect (Activity Act) {</P> <p> connectivitymanager manager = (connectivitymanager) Act <br/>. getapplicationcontext (). getsystemservice (<br/> context. connectivity_service); </P> <p> If (Manager = NULL) {<br/> return false; <br/>}</P> <p> networkinfo = manager. getactivenetworkinfo (); </P> <p> If (networkinfo = NULL |! Networkinfo. isavailable () {<br/> return false; <br/>}</P> <p> return true; <br/>}< br/>}
This class has only one static method to check whether the network of the current system is available. If available, return true.
It should be further noted that the networkinfo class has a method GetType (), which can be used to determine whether the current available network is WIFI or mobile.
Let's take a look at the example.
Boolean networkstate = networkdetector. Detect (xxxactivity. This); <br/> If (! Networkstate) {<br/> dialogutil. openmsgdialog (xxxactivity. this, <br/> android. r. drawable. ic_dialog_info, <br/> "the network is unavailable. Do you want to set the network now? ", Android. r. string. OK, <br/> android. r. string. cancel, <br/> New dialoginterface. onclicklistener () {<br/> @ override <br/> Public void onclick (dialoginterface dialog, int which) {<br/> startactivityforresult (new intent (<br/> action_wireless_settings), 0); <br/>}< br/>}, new dialoginterface. onclicklistener () {<br/> @ override <br/> Public void onclick (dialoginterface dialog, int which) {<br/> dialog. cancel (); <br/>}< br/> }). show (); <br/>}
Among them, xxxactivity is my own activity class, And dialogutil is my custom dialog application class. The code snippet displays a dialog box Indicating whether to enter the network settings page of the system when no network is available.
Because the above Code uses the permission, you need to add the following permission code to the androidmanifest file:
<Uses-Permission
Android: Name ="Android. Permission. access_network_state"
/>
---------------------------------------------------------------------------
GL (arui319)
Http://blog.csdn.net/arui319
<This article can be reproduced, but please keep the above author information. Thank you.>
---------------------------------------------------------------------------