NetWorkReceive in android and get the current network connection status

Source: Internet
Author: User

NetWorkReceive in android and get the current network connection status

Now, it is absolutely difficult for an APP to survive without the network, and there will be many frequent network operations, request data, and transmit data. Therefore, we need to have a better understanding of the network status.

First, if our APP is running, if the user is disconnected and there is no network, we should prompt the user and connect the user to the network, we should also remind the user at this time so that he can continue to play with our APP. What should we do? Yes, it is implemented through the aggreger, because both the disconnected network and the networked system send broadcasts, we can then receive them and determine whether the current network is available through broadcasts. The specific code is as follows: the action required to receive broadcasts is android.net. conn. CONNECTIVITY_CHANGE and ta.android.net. conn. CONNECTIVITY_CHANGE. We need to add a filter when registering the broadcast receiver so that the receiver can receive the filter.

Import com. iyueju. guanggong. util. netWorkUtil; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. util. log; import android. widget. toast;/*** receiver used to accept changes in network status ** @ author Administrator **/public class NetWorkReceiver extends BroadcastReceiver {private static Boolean networkAvailable = false; // The default network status is private static com. iyueju. guanggo Ng. util. netWorkUtil. netType type; private final static String ANDROID_NET_CHANGE_ACTION = android.net. conn. CONNECTIVITY_CHANGE; public final static String TA_ANDROID_NET_CHANGE_ACTION = ta.android.net. conn. CONNECTIVITY_CHANGE; private static NetWorkReceiver receiver; private NetWorkReceiver () {super ();} public static NetWorkReceiver getNetWorkReceiver () {// TODO Auto-generated constructor stubif (receive R = null) {synchronized (networkcycler. class) {if (receiver = null) {receiver = new NetWorkReceiver () ;}} return receiver ;}@ Overridepublic void onReceive (Context context, Intent intent) {// TODO Auto-generated method stureceiver = NetWorkReceiver. this; if (intent. getAction (). equalsIgnoreCase (ANDROID_NET_CHANGE_ACTION) | intent. getAction (). equalsIgnoreCase (TA_ANDROID_NET_CHANGE_ACTION) {Log. I (Main, Message about network connection received); if (! NetWorkUtil. isNetworkAvailable (context) & networkAvailable = true) {Log. I (Main, disconnected from the network); networkAvailable = false; Toast. makeText (context, network unavailable, 1 ). show ();} else if (NetWorkUtil. isNetworkAvailable (context) & networkAvailable = false) {Log. I (Main, network connection successful); networkAvailable = true; type = NetWorkUtil. getAPNType (context); Toast. makeText (context, network connection successful, 1 ). show () ;}}/*** register a network listener ** @ param context */publ Ic static void registerNetworkStateReceiver (Context context) {Intent intent = new Intent (); intent. setAction (TA_ANDROID_NET_CHANGE_ACTION); context. sendBroadcast (intent);}/*** displays the current network status ** @ param context */public static void checkNetWorkState (Context context) {Intent intent Intent = new intent (); intent. setAction (TA_ANDROID_NET_CHANGE_ACTION); context. sendBroadcast (intent);}/*** disconnect the network listener ** @ param context */p Ublic static void unRegisterNetworkStateReceiver (Context context) {if (receiver! = Null) {try {context. getApplicationContext (). unregisterReceiver (receiver);} catch (Exception e) {e. printStackTrace () ;}} public static Boolean isNetWorkAvailable () {return networkAvailable;} public static com. iyueju. guanggong. util. netWorkUtil. netType getNetWorkType () {return type ;}}

Registration listening:

/*** Register the listener */private void registerMessageReceiver () {// TODO Auto-generated method stubNetWorkReceiver receiver = NetWorkReceiver. getNetWorkReceiver (); IntentFilter filter = new intentfilter(registry.filter.addaction(android.net.conn.connectivity_change%;filter.addaction(android.gz cpc. conn. CONNECTIVITY_CHANGE); registerReceiver (receiver, filter );}


Then, you need to log out when the APP is not applicable.

Then:

unregisterReceiver(NetWorkReceiver.getNetWorkReceiver());


Then, in our APP, we trigger some network operations through some view clicks or other events. To avoid some errors, we need to first determine whether the current network is available, the current connected network is not wifi (for your consideration), whether there is a network connection, how fast the current network is, and whether it is suitable for our operations.

The specific code implementation is as follows:

Import java. io. IOException; import java. io. inputStream; import java.net. malformedURLException; import java.net. URL; import java.net. URLConnection; import com. iyueju. guanggong. constant. APPConstant; import android. content. context; import android.net. connectivityManager; import android.net. networkInfo; import android. OS. handler; import android. OS. message; import android. util. log;/*** network tool class ** @ author Administr Ator **/public class NetWorkUtil {// Private fieldsprivate static final String TAG = NetWorkUtil. class. getSimpleName (); private static final int handle = 1048576; // 1 MB 1024*1024 private static final double BYTE_TO_KILOBIT = 0.0078125; private static final double KILOBIT_TO_MEGABIT = 0.0009765625; private static Handler mHandler; public static int timer; // network status, connection to wifi, cmnet is directly connected to the Internet, cmwap Yes proxy is required. noneNet is connectionless // for speed purposes: wifi> cmnet> cmwap> noneNetpublic static enum netType {wifi, CMNET, CMWAP, noneNet}/*** network availability ** @ param context * @ return */public static boolean isNetworkAvailable (Context context) {// obtain the network managerConnectivityManager mgr = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo [] info = mgr. getAllNetworkInfo (); // traverses all accessible networks if (info! = Null) {for (int I = 0; I <info. length; I ++) {if (info [I]. getState () = NetworkInfo. state. CONNECTED) {return true ;}} return false;}/*** determine whether a network connection exists ** @ param context * @ return */public static boolean isNetworkConnected (Context context) {if (context! = Null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager. getActiveNetworkInfo (); if (mNetworkInfo! = Null) {return mNetworkInfo. isAvailable () ;}} return false;}/*** determine whether the Wi-Fi network is available ** @ param context * @ return */public static boolean isWifiConnected (Context context) {if (context! = Null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo networking = mConnectivityManager. getNetworkInfo (ConnectivityManager. TYPE_WIFI); if (mWiFiNetworkInfo! = Null) {return mWiFiNetworkInfo. isAvailable () ;}} return false;}/*** determine whether the MOBILE network is available ** @ param context * @ return */public static boolean isMobileConnected (Context context) {if (context! = Null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo networking = mConnectivityManager. getNetworkInfo (ConnectivityManager. TYPE_MOBILE); if (mMobileNetworkInfo! = Null) {return mMobileNetworkInfo. isAvailable () ;}} return false;}/*** obtain the type information of the current network connection ** @ param context * @ return */public static int getConnectedType (Context context) {if (context! = Null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager. getActiveNetworkInfo (); if (mNetworkInfo! = Null & mNetworkInfo. isAvailable () {return mNetworkInfo. getType () ;}} return-1;}/***** @ author white cat ** get the current network status-1: No network 1: WIFI network 2: wap network 3: net network ** @ param context ** @ return */public static netType getAPNType (Context context) {ConnectivityManager connMgr = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr. getActiveNetworkInfo (); if (net WorkInfo = null) {return netType. noneNet;} int nType = networkInfo. getType (); if (nType = ConnectivityManager. TYPE_MOBILE) {if (networkInfo. getExtraInfo (). toLowerCase (). equals (cmnet) {return netType. CMNET;} else {return netType. CMWAP ;}} else if (nType = ConnectivityManager. TYPE_WIFI) {return netType. wifi;} return netType. noneNet;}/*** test network speed ** @ param handler */public static void textSpeed (Handler hand Ler) {mHandler = handler; new Thread (mWorker ). start ();}/*** Our Slave worker that does actually all the work */private static final Runnable mWorker = new Runnable () {@ Overridepublic void run () {InputStream stream = null; try {int bytesIn = 0; String downloadFileUrl = http: // 120.24.237.77/test; long startCon = System. currentTimeMillis (); URL url = new URL (downloadFileUrl); URLConnection con = url. openConne Ction (); con. setUseCaches (false); long connectionLatency = System. currentTimeMillis ()-startCon; stream = con. getInputStream (); Message msgUpdateConnection = Message. obtain (mHandler, APPConstant. MSG_UPDATE_CONNECTION_TIME); msgUpdateConnection. arg1 = (int) connectionLatency; mHandler. sendMessage (msgUpdateConnection); long start = System. currentTimeMillis (); int currentByte = 0; long updateStart = System. c UrrentTimeMillis (); long updateDelta = 0; int bytesInThreshold = 0; while (currentByte = stream. read ())! =-1) {bytesIn ++; bytesInThreshold ++; if (updateDelta> = APPConstant. UPDATE_THRESHOLD) {int progress = (int) (bytesIn/(double) EXPECTED_SIZE_IN_BYTES) * 100); Message msg = Message. obtain (mHandler, APPConstant. MSG_UPDATE_STATUS, calculate (updateDelta, bytesInThreshold); msg. arg1 = progress; msg. arg2 = bytesIn; mHandler. sendMessage (msg); // ResetupdateStart = System. currentTimeMillis (); bytesInThreshold = 0;} updateDelta = System. currentTimeMillis ()-updateStart;} long downloadTime = (System. currentTimeMillis ()-start); // Prevent AritchmeticExceptionif (downloadTime = 0) {downloadTime = 1;} Message msg = Message. obtain (mHandler, APPConstant. MSG_COMPLETE_STATUS, calculate (downloadTime, bytesIn); msg. arg1 = bytesIn; mHandler. sendMessage (msg);} catch (MalformedURLException e) {Log. e (TAG, e. getMessage ()) ;} Catch (IOException e) {Log. e (TAG, e. getMessage ();} finally {try {if (stream! = Null) {stream. close () ;}} catch (IOException e) {// Suppressed }}}}; /***** 1 byte = 0.0078125 kilobits 1 kilobits = 0.0009765625 megabit ** @ param downloadTime * in miliseconds * @ param bytesIn * number of bytes downloaded * @ return SpeedInfo containing current speed * /private static SpeedInfo calculate (final long downloadTime, final long bytesIn) {SpeedInfo info = new SpeedInfo (); // from mil to seclong bytespersecond = (bytesIn/downloadTime) * 1000; double kilobits = bytespersecond * BYTE_TO_KILOBIT; double megabits = kilobits * KILOBIT_TO_MEGABIT; info. downspeed = bytespersecond; info. kilobits = kilobits; info. megabits = megabits; return info;}/*** Transfer Object ** @ author dedevil **/public static class SpeedInfo {public double kilobits = 0; public double megabits = 0; public double downspeed = 0 ;}}


Four other constants are involved:

public static final int MSG_UPDATE_STATUS = 0;public static final int MSG_UPDATE_CONNECTION_TIME = 1;public static final int MSG_COMPLETE_STATUS = 2;public static final int UPDATE_THRESHOLD = 300;


Note: You need to add some permissions when using them,

 

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.