Networkreceive in Android and get the current network connection status in detail

Source: Internet
Author: User

We now the app is decidedly difficult to leave the network to survive, there will be a lot of very frequent network operations, request data, transfer data and so on, so we need to have a little more understanding of network status.

First, if our app is running, if the user dropped the line, there is no network, we should give the user prompt, and then the user connected to the network, we should also give the user prompt, so he can continue to play our app, we should do, yes, is achieved through receiver, because the network and networking system will send a broadcast, and then we can receive, broadcast to determine whether the current network is available, the code is as follows: where the action to accept the broadcast is " Android.net.conn.CONNECTIVITY_CHANGE "and" Ta.android.net.conn.CONNECTIVITY_CHANGE ", we need to register the broadcast receiver when adding a filter so that he can receive it.

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 that accepts changes in network status * * @author Administrator * */public class Networkreceiver extends Broadcastreceiver{private static Boolean networkavailable = false;//default network state private static Com.iyueju.guanggong.util.NetWorkUtil.netType Type;private Final static string android_net_change_action = "Android.net.conn.CONNECTIVITY_CHANGE";p ublic final static string Ta_ Android_net_change_action = "Ta.android.net.conn.CONNECTIVITY_CHANGE";p rivate static networkreceiver receiver; Private Networkreceiver () {super ();} public static Networkreceiver Getnetworkreceiver () {//TODO auto-generated constructor stubif (receiver = = null) { Synchronized (Networkreceiver.class) {if (receiver = = NULL) {receiver = new networkreceiver ();}}} return receiver;} @Overridepublic void OnReceive (context context, Intent Intent) {//TODOAuto-generated Method stureceiver = networkreceiver.this;if (Intent.getaction (). Equalsignorecase (ANDROID_NET_CHANGE _action) | | Intent.getaction (). Equalsignorecase (ta_android_net_change_action)) {log.i ("Main", "There is a message about receiving an Internet connection"); Networkutil.isnetworkavailable (context) && networkavailable = = True) {log.i ("Main", "Disconnected network"); Networkavailable = false; Toast.maketext (Context, "Network unavailable", 1). Show (); else if (networkutil.isnetworkavailable (context) && networkavailable = = False) {log.i ("Main", "Network connection succeeded"); networkavailable = True;type = Networkutil.getapntype (context); Toast.maketext (Context, "Network connection succeeded", 1). Show ();}}} /** * Register Network Monitor * * @param context */public static void Registernetworkstatereceiver (context context) {Intent Intent = new in Tent (); intent.setaction (ta_android_net_change_action); Context.sendbroadcast (intent);} /** * Display current network status * * @param context */public static void Checknetworkstate (context context) {Intent Intent = new Intent (); in Tent.setaction (ta_android_net_change_action); conText.sendbroadcast (intent);} /** * Logoff Network Listener * * @param context */public 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;}}

Register for monitoring:

/** * Register monitor */private void Registermessagereceiver () {//TODO auto-generated method Stubnetworkreceiver receiver = Networkre Ceiver.getnetworkreceiver (); intentfilter filter = new Intentfilter (); Filter.addaction (" Android.net.conn.CONNECTIVITY_CHANGE "); Filter.addaction (" Android.gzcpc.conn.CONNECTIVITY_CHANGE "); Registerreceiver (receiver, filter);}


Then, you need to log out when the app is not available

is the following:

Unregisterreceiver (Networkreceiver.getnetworkreceiver ());


Then, if it is in our app, we use some view of the click or other events to trigger some network operations, in order to avoid some errors, we need to determine whether the current network is available, the network is not currently connected to WiFi (for the user) and whether there is currently a network connection, There are the current speed is how big, whether it is suitable for our operation and so on.

The following is a specific code implementation:

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 Administrator * */public class networkutil{//Private Fieldsprivate static final String TAG = NetWorkUtil.class.getSimpleName ();p rivate static final int expected_size_in_ BYTES = 1048576;//1MB 1024*1024private static final double byte_to_kilobit = 0.0078125;private static final double Kilobi T_to_megabit = 0.0009765625;private static Handler mhandler;public static int timer;//network State, connection wifi,cmnet is directly connected to the Internet, Cmwap is need agent, nonenet is no connection//one speed: WiFi > Cmnet >cmwap > Nonenetpublic static enum Nettype{wifi, Cmnet, Cmwap, Nonen et}/** * Network Available * * @param context * @return */public static Boolean IsnetworkavAilable (Context context) {//get network Managerconnectivitymanager mgr = (connectivitymanager) Context. Getsystemservice ( Context.connectivity_service); Networkinfo[] info = mgr.getallnetworkinfo ();//traverse all networks that can be connected if (info! = null) {for (int i = 0; i < info.length; i++) {if ( Info[i].getstate () = = NetworkInfo.State.CONNECTED) {return true;}}} return false;} /** * Determine if there is an Internet connection * * @param context * @return */public static Boolean isnetworkconnected (context context) {if (Context! = N ull) {Connectivitymanager Mconnectivitymanager = (connectivitymanager) context. Getsystemservice ( Context.connectivity_service); Networkinfo mnetworkinfo = Mconnectivitymanager.getactivenetworkinfo (); if (mnetworkinfo! = null) {return Mnetworkinfo.isavailable ();}} return false;} /** * Determine if WiFi network is available * * @param context * @return */public static Boolean iswificonnected (context context) {if (Context! = N ull) {Connectivitymanager Mconnectivitymanager = (connectivitymanager) context. Getsystemservice ( Context.connectivity_service); NetWorkinfo mwifinetworkinfo = Mconnectivitymanager. Getnetworkinfo (Connectivitymanager.type_wifi); if ( Mwifinetworkinfo! = null) {return mwifinetworkinfo.isavailable ();}} return false;} /** * Determine if 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 mmobilenetworkinfo = Mconnectivitymanager. Getnetworkinfo (Connectivitymanager.type_mobile); if ( Mmobilenetworkinfo! = null) {return mmobilenetworkinfo.isavailable ();}} return false;} /** * Gets the type information of the current network connection * * @param context * @return */public static int Getconnectedtype (context context) {if (Context! = nul L) {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 current network status-1: No network 1:wifi network 2:WAP Network 3:net Network * * @param context * * @return */public Stati C NetType Getapntype (context context) {Connectivitymanager connmgr = (connectivitymanager) context. Getsystemservice (Co ntext. Connectivity_service); Networkinfo networkinfo = Connmgr.getactivenetworkinfo (); if (networkinfo = = 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 speed * * @param handler */public static void Textspeed (handler handler) {Mhandler = Handler;new Thread (mworker). Star T ();} /** * Our Slave worker, does actually all the work */private static final Runnable mworker = new Runnable () {@Overridep ublic 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.openconnection (); 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.currenttimemillis (); 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 = b Ytesin;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 kilo Bits 1 kilobits = 0.0009765625 megabit * * @param downloadtime * in miliseconds * @param bytesin * Numb Er of bytes downloaded * @return Speedinfo containing current speed */private static Speedinfo calculate (final long Downlo Adtime, Final long bytesin) {Speedinfo info = new Speedinfo ();//FRom mil to Seclong Bytespersecond = (bytesin/downloadtime) * 1000;double kilobits = Bytespersecond * Byte_to_kilobit;dou ble megabits = kilobits * Kilobit_to_megabit;info.downspeed = Bytespersecond;info.kilobits = Kilobits;info.megabits = Meg Abits;return info;} /** * Transfer Object * * @author Devil * */public static class Speedinfo{public Double kilobits = 0;public double Megabi ts = 0;public Double downspeed = 0;}}


Of these, 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 I NT Msg_complete_status = 2;public static final int update_threshold = 300;


Note: You need to add some permissions when you use it.

, such as check the WiFi status, please see: http://blog.csdn.net/liweijie_chengxuyuan/article/details/41822883

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Networkreceive in Android and get the current network connection status in detail

Related Article

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.