185-3825-9583
首页

如何通过广播监听网络状态的代码实现

网络状态 2018-04-23 452

一般我们打开无线有时候会主动连接上一些没有密匙的无线网络,但是这时候手机上的应用程序仍然显示的是没有有效的数据连接,那么除了用浏览器打开检测之外,其实还有一种比较有效的办法,那就是通过广播监听网络状态,下面app开发报价淘金科技跟大家分享一下实现代码:

权限

<uses-permission android:name="android.permission.INTERNET"/>

 <!--允许读取网络状态-->

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

<!--允许读取wifi网络状态-->

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

通过广播监听网络状态的两种方法

静态注册

<receiver android:name=".network.NetworkConnectChangedReceiver">

    <intent-filter>

        <action android:name="android.NET.conn.CONNECTIVITY_CHANGE" />

        <action android:name="android.Net.wifi.WIFI_STATE_CHANGED" />

        <action android:name="android.net.wifi.STATE_CHANGE" />

    </intent-filter>

</receiver> 

动态注册 

第一步:在AndroidMainest文件里面注册 

<receiver android:name=".network.NetworkConnectChangedReceiver">

        </receiver> 

第二步:调用 Context registerReceiver(Receiver,IntentFilter) 进行注册 

IntentFilter filter = new IntentFilter();

filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");

filter.addAction("android.net.wifi.STATE_CHANGE");

registerReceiver(mNetworkChangeListener,filter);

使用我们自定义的NetworkChangeListener广播 

至于广播的Action主要有三种类型: 

WifiManager.WIFI_STATE_CHANGED_ACTION 

这个监听wifi的打开与关闭,与wifi的连接无关

WifiManager.NETWORK_STATE_CHANGED_ACTION 

这个监听wifi的连接状态即是否连上了一个有效无线路由,

当上边广播的状态是WifiManager.WIFI_STATE_DISABLING

WIFI_STATE_DISABLED的时候,根本不会接到这个广播。

在上边广播接到广播是WifiManager.WIFI_STATE_ENABLED状态的同时也会接到这个广播,

当然刚打开wifi肯定还没有连接到有效的无线

ConnectivityManager.CONNECTIVITY_ACTION

这个监听网络连接的设置,包括wifi和移动数据的打开和关闭。.

最好用的还是这个监听。wifi如果打开,关闭,以及连接上可用的连接都会接到监听。

这个广播的最大弊端是比上边两个广播的反应要慢,如果只是要监听wifi

我觉得还是用上边两个配合比较合适。

/**

 * 网络改变监控广播

 * <p>

 * 监听网络的改变状态,只有在用户操作网络连接开关(wifi,mobile)的时候接受广播,

 * 然后对相应的界面进行相应的操作,并将 状态 保存在我们的APP里面

 * <p>

 * <p>

 * Created by xujun

 */

public class NetworkConnectChangedReceiver extends BroadcastReceiver {

    private static final String TAG = "xujun";

    public static final String TAG1 = "xxx";

    @Override

    public void onReceive(Context context, Intent intent) {

        // 这个监听wifi的打开与关闭,与wifi的连接无关

        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {

            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);

            Log.e(TAG1, "wifiState" + wifiState);

            switch (wifiState) {

                case WifiManager.WIFI_STATE_DISABLED:

                    APP.getInstance().setEnablaWifi(false);

                    break;

                case WifiManager.WIFI_STATE_DISABLING:

                    break;

                case WifiManager.WIFI_STATE_ENABLING:

                    break;

                case WifiManager.WIFI_STATE_ENABLED:

                    APP.getInstance().setEnablaWifi(true);

                    break;

                case WifiManager.WIFI_STATE_UNKNOWN:

                    break;

                default:

                    break;

            }

        }

        // 这个监听wifi的连接状态即是否连上了一个有效无线路由,当上边广播的状态是WifiManager

        // .WIFI_STATE_DISABLING,和WIFI_STATE_DISABLED的时候,根本不会接到这个广播。

        // 在上边广播接到广播是WifiManager.WIFI_STATE_ENABLED状态的同时也会接到这个广播,

        // 当然刚打开wifi肯定还没有连接到有效的无线

        if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {

            Parcelable parcelableExtra = intent

                    .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

            if (null != parcelableExtra) {

                NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;

                State state = networkInfo.getState();

                boolean isConnected = state == State.CONNECTED;// 当然,这边可以更精确的确定状态

                Log.e(TAG1, "isConnected" + isConnected);

                if (isConnected) {

                    APP.getInstance().setWifi(true);

                } else {

                    APP.getInstance().setWifi(false);

                }

            }

        }

        // 这个监听网络连接的设置,包括wifi和移动数据的打开和关闭。.

        // 最好用的还是这个监听。wifi如果打开,关闭,以及连接上可用的连接都会接到监听。见log

        // 这个广播的最大弊端是比上边两个广播的反应要慢,如果只是要监听wifi,我觉得还是用上边两个配合比较合适

        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {

            ConnectivityManager manager = (ConnectivityManager) context

                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            Log.i(TAG1, "CONNECTIVITY_ACTION");

            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();

            if (activeNetwork != null) { // connected to the internet

                if (activeNetwork.isConnected()) {

                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {

                        // connected to wifi

                        APP.getInstance().setWifi(true);

                        Log.e(TAG, "当前WiFi连接可用 ");

                    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {

                        // connected to the mobile provider's data plan

                        APP.getInstance().setMobile(true);

                        Log.e(TAG, "当前移动网络连接可用 ");

                    }

                } else {

                    Log.e(TAG, "当前没有网络连接,请确保你已经打开网络 ");

                }

                Log.e(TAG1, "info.getTypeName()" + activeNetwork.getTypeName());

                Log.e(TAG1, "getSubtypeName()" + activeNetwork.getSubtypeName());

                Log.e(TAG1, "getState()" + activeNetwork.getState());

                Log.e(TAG1, "getDetailedState()"

                        + activeNetwork.getDetailedState().name());

                Log.e(TAG1, "getDetailedState()" + activeNetwork.getExtraInfo());

                Log.e(TAG1, "getType()" + activeNetwork.getType());

            } else {   // not connected to the internet

                Log.e(TAG, "当前没有网络连接,请确保你已经打开网络 ");

                APP.getInstance().setWifi(false);

                APP.getInstance().setMobile(false);

                APP.getInstance().setConnected(false); 

            }

        }

    }

}

public class NetStateUtils {

    /**

     * 判断当前网络是否是移动网络

     *

     * @param context

     * @return boolean

     */

    public static boolean is3G(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null

                && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {

            return true;

        }

        return false;

    }

    /**

     * 判断当前网络是否是wifi网络

     *

     * @param context

     * @return boolean

     */

    public static boolean isWifi(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null

                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {

            return true;

        }

        return false;

    }

    /**

     * 判断当前网络是否是2G网络

     *

     * @param context

     * @return boolean

     */

    public static boolean is2G(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetInfo != null

                && (activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE

                || activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || activeNetInfo

                .getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA)) {

            return true;

        }

        return false;

    }

 

    /**

     * wifi是否打开

     */

    public static boolean isWifiEnabled(Context context) {

        ConnectivityManager mgrConn = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        TelephonyManager mgrTel = (TelephonyManager) context

                .getSystemService(Context.TELEPHONY_SERVICE);

        return ((mgrConn.getActiveNetworkInfo() != null && mgrConn

                .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel

                .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);

    }

 

    /**

     * 判断是否有网络连接

     *

     * @param context

     * @return

     */

    public static boolean isNetworkConnected(Context context) {

        if (context != null) {

            // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)

            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context

                    .CONNECTIVITY_SERVICE);

            // 获取NetworkInfo对象

            NetworkInfo networkInfo = manager.getActiveNetworkInfo();

            //判断NetworkInfo对象是否为空

            if (networkInfo != null)

                return networkInfo.isAvailable();

&nb

分享到微信朋友圈 +
打开微信,点击底部的“发现”,使用 “扫一扫” 即可将网页分享到我的朋友圈。 如何使用?
推荐文章

热贴More +

服务范围More +

联系我们

请扫二维码联系客服

854221200@qq.com

185-3825-9583

QQ客服

关于  ·  招聘  ·  案例中心  ·  网站地图

(c)@2018 淘金科技版权所有 豫ICP备16015002号-4

百度提供搜索支持