Android detects network connection and android Detection

Source: Internet
Author: User

Android detects network connection and android Detection

Permission:

<Uses-permission android: name = "android. permission. ACCESS_NETWORK_STATE"/>
<Uses-permission android: name = "android. permission. ACCESS_WIFI_STATE"/>

The Code is as follows:

Package com. example. nettest;

Import android.net. ConnectivityManager;
Import android.net. NetworkInfo. State;
Import android. OS. Bundle;
Import android. app. Activity;
Import android. app. AlertDialog;
Import android. content. ComponentName;
Import android. content. Context;
Import android. content. DialogInterface;
Import android. content. Intent;
Import android. view. Menu;
Import android. widget. TextView;
Import android. widget. Toast;


Public class MainActivity extends Activity {


Private ConnectivityManager manager;
Private TextView TV;
StringBuffer sb = new StringBuffer (256 );


@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );


TV = (TextView) findViewById (R. id. textView1 );
CheckNetworkState ();
}


/**
* Check whether the network is connected
*
* @ Return
*/
Private boolean checkNetworkState (){
Boolean flag = false;
// Obtain the network connection information
Manager = (ConnectivityManager) getSystemService (Context. CONNECTIVITY_SERVICE );
// Determine whether the network is connected
If (manager. getActiveNetworkInfo ()! = Null ){
Flag = manager. getActiveNetworkInfo (). isAvailable ();
}
If (! Flag ){
SetNetwork ();
} Else {
IsNetworkAvailable ();
}
TV. setText (sb. toString ());
Return flag;
}


/**
* When the network is not connected, call the setting method.
*/
Private void setNetwork (){
Toast. makeText (this, "wifi is closed! ", Toast. LENGTH_SHORT). show ();
AlertDialog. Builder builder = new AlertDialog. Builder (this );
Builder. setIcon (R. drawable. ic_launcher );
Builder. setTitle ("Network prompt information ");
Builder. setMessage ("the network is unavailable. If you want to continue, set the network first! ");
Builder. setPositiveButton ("set", new DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Intent intent = null;
/**
* Determine the version of the mobile phone system! If the API is greater than 10, it is 3.0 +. Because the setting of version 3.0 or later is different from that of version 3.0 or lower, the called method is different.
*/
If (android. OS. Build. VERSION. SDK_INT> 10 ){
Intent = new Intent (
Android. provider. Settings. ACTION_SETTINGS );
} Else {
Intent = new Intent ();
ComponentName component = new ComponentName (
"Com. android. settings ",
"Com. android. settings. WirelessSettings ");
Intent. setComponent (component );
Intent. setAction ("android. intent. action. VIEW ");
}
StartActivity (intent );
}
});


Builder. setNegativeButton ("cancel", new DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
}
});
Builder. create ();
Builder. show ();
}


/**
* The network is connected, and then you can determine whether the Wi-Fi connection or GPRS connection has set some logical calls.
*/
Private void isNetworkAvailable (){


State gprs = manager. getNetworkInfo (ConnectivityManager. TYPE_MOBILE)
. GetState ();
State wifi = manager. getNetworkInfo (ConnectivityManager. TYPE_WIFI)
. GetState ();
If (gprs = State. CONNECTED | gprs = State. CONNECTING ){
Toast. makeText (this, "gprs is open! ", Toast. LENGTH_SHORT). show ();
Sb. append ("\ ngprs is open! ");
} Else {
Sb. append ("\ ngprs is closed! ");
}


// The advertisement is loaded only when it is determined to be wifi. If it is a GPRS mobile phone network, it is not loaded!
If (wifi = State. CONNECTED | wifi = State. CONNECTING ){
Toast. makeText (this, "wifi is open! ", Toast. LENGTH_SHORT). show ();
LoadAdmob ();
Sb. append ("\ nwifi is open! ");
} Else {
Sb. append ("\ nwifi is closed! ");
}


}


/**
* Admob advertisement loading in wifi status
*/
Private void loadAdmob (){
Toast. makeText (getApplicationContext (), "ad is loding...", 1). show ();
Sb. append ("\ NADIS loding ...");
}
}


How to determine the network connection status of the Android Series

Let's discuss the technical implementation of judging the network connection status of Android phones.
Currently, most Android mobile phones support WIFI,
GSM, 3G network communication
But you can select only one connection method each time you link to the network,
For example, a carrier must also require a specific network environment (CMWAP, CTWAP, etc.) to switch the network, you must first disable the existing network,
Then start a new network. The conversion process takes some time,
At this time, you may also need to know whether the network connection is successful and then automatically log on to the new network server,
A thread may be used to monitor whether the connection to the network status is successful;
We can use another method, PhoneStateListener
That's right. You are not mistaken. You just use PhoneStateListener.
Many applications use PhoneStateListener to listen for calls to power-off. PhoneStateListener can also listen for network disconnection,
The connection is successful.
1 final TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService (Context. TELEPHONY_SERVICE );
2 mTelephonyMgr. listen (new PhoneStateListener (){
3
4 @ Override
5 public void onDataConnectionStateChanged (int state ){
6 switch (state ){
7 case TelephonyManager. DATA_DISCONNECTED: // The network is disconnected.
8 break;
9 case TelephonyManager. DATA_CONNECTING: // The network is being connected.
10 break;
11 case TelephonyManager. DATA_CONNECTED: // network connection
12 break;
13} 14} 15 16} PhoneStateListener. LISTEN_DATA_CONNECTION_STATE );
We only need to reload the onDataConnectionStateChanged method and make corresponding processing based on the state judgment.

How does android determine whether the network is connected?

Public static boolean networkStatusOK (Context mContext ){
Boolean netStatus = false;
Try {
ConnectivityManager connectManager = (ConnectivityManager) Context. getSystemService (Context. CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectManager. getActiveNetworkInfo ();
If (activeNetworkInfo! = Null ){
If (activeNetworkInfo. isAvailable () & activeNetworkInfo. isConnected ()){
NetStatus = true;
}
}
} Catch (Exception e) {e. printStackTrace ();}
Return netStatus;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.