关闭

Broadcast Receiver监听网络状态

标签: broadcast
62人阅读 评论(0) 收藏 举报
分类:

在代码中动态注册,不需要在AndroidManifest.xml里静态注册,静态注册在不打开App的情况下,有可以接收到广播。

public class MainActivity extends Activity {
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//监听网络的状态;网络状态改变就会被调动。
    networkChangeReceiver = new NetworkChangeReceiver();
    registerReceiver(networkChangeReceiver, intentFilter);
}
@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(networkChangeReceiver);
    }
}

创建NetworkChangeReceiver类继承BroadcaseReceiver

class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//枚举 enum NetworkStatus {DisConnect,Mobile,Wifi}
    ConfigConstant.NetworkStatus status
    =getConnectType();
    switch(status){
        case DisConnect:

        break;
        case Mobile:

        break;
        case Wifi:

        break;
    }
}
/*
*获取网络状态,
*/
private ConfigConstant.NetworkStatus getConnectType() {
    ConnectivityManager connMgr =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();

    if (activeInfo != null && activeInfo.isConnected()){
        if (activeInfo.getType() == ConnectivityManager.TYPE_WIFI)
            return ConfigConstant.NetworkStatus.Wifi;
        else if (activeInfo.getType() == ConnectivityManager.TYPE_MOBILE)
            return ConfigConstant.NetworkStatus.Mobile;
    }
    return ConfigConstant.NetworkStatus.DisConnect;
}

网络状态一旦发生改变,会调用NetworkChangeReceiver 的onReceive(),再去获取网络状态。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:314次
    • 积分:51
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档