您的位置:首页 > 理论基础 > 计算机网络

Android之监测手机网络状态的广播

2016-04-07 19:03 411 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。

今天具体说下Android检测网络状态的广播,我们在做一些手机应用的时候如果网络发生改变可能会给用户造成一些损失,在中国2G,3G网络都没有普及的情况下,基本都是包流量的,所以在做一些视频应用软件的时候,如果用户在使用WIFI的时候如果无线网络中断,手机网络会自动换手机网络,从而给用户造成不必要的损失。

Android手机在对于一些系统广播,如短信的接收,电话的接收,电池电量过低,网络状态改变都会发一个广播,既然系统会发送一条广播,那么就需要一个接收器来处理这个广播。首先定义一个类继承NetworkChangeReceiver,重写onReceive()就行了。然后在OnReceive()这个方法进行相应广播的处理。

网络状态切换的广播类:

[java] view
plain copy

package com.test;  

  

import android.content.BroadcastReceiver;  

import android.content.Context;  

import android.content.Intent;  

import android.net.ConnectivityManager;  

import android.net.NetworkInfo.State;  

  

public class extends BroadcastReceiver {  

  

    @Override  

    public void onReceive(Context context, Intent intent) {  

        State wifiState = null;  

        State mobileState = null;  

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  

        wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();  

        mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();  

        if (wifiState != null && mobileState != null  

                && State.CONNECTED != wifiState  

                && State.CONNECTED == mobileState) {  

            // 手机网络连接成功  

        } else if (wifiState != null && mobileState != null  

                && State.CONNECTED != wifiState  

                && State.CONNECTED != mobileState) {  

            // 手机没有任何的网络  

        } else if (wifiState != null && State.CONNECTED == wifiState) {  

            // 无线网络连接成功  

        }  

  

    }  

  

}  

在上面这个接收类中OnReceive()方法,你可以在上面三个网络状态(只有手机网络,只有无线网络,没有任何网络)中进行相应的处理,然后在应用中注册广播,注册广播有2种方式,一种在androidmanifest.xml中注册,一种在java代码中注册。

第一种:

[html] view
plain copy

<receiver  

    android:name="com.test.NetworkBroadcast"  

    android:label="NetworkConnection" >  

    <intent-filter>  

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

    </intent-filter>  

</receiver>  

第二种:

可以在Activity的onCreate()方法中注册广播,在Activity的onDestory()方法中卸载广播。

[java] view
plain copy

private BroadcastReceiver networkBroadcast=new BroadcastReceiver();  

[java] view
plain copy

        private void registerNetworkReceiver() {  

    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);  

    this.registerReceiver(networkBroadcast, filter);  

}  

  

private void unRegisterNetworkReceiver() {  

        this.unregisterReceiver(networkBroadcast);  

}  

注意:在接收类中的onReceive()方法中不要处理太多复杂逻辑问题,尤其耗时的操作。

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息