Android 的网络链接状态

Android手机对于系统状态的改变 ,如:信的接收,电话的接收,电池电量过低,网络状态改变都会发一个广播 。有了广播机制,我们只需要创建一个广播接受者来处理这个广播,就可以实现在不同状态下做出不同的操作、

本篇主要记录一下对于网络状态改变的监听。首先定义一个类继承NetworkChangeReceiver,重写onReceive()就行了。然后在OnReceive()这个方法进行相应广播的处理。

public class NetWorkReceiver extends BroadcastReceiver {
  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 (mobileState != null && State.CONNECTED == mobileState) { // 手机网络连接成功 if (cm.getActiveNetworkInfo().getExtraInfo().toLowerCase() .equals("cmnet")) { //cmnet链接 }else{ // cmwap链接,添加中国移动代理

                HttpHost proxy = new HttpHost("10.0.0.172", 80); 

                conn = (HttpURLConnection) url.openConnection(proxy);

                 }
        } else if (State.CONNECTED != wifiState
                && State.CONNECTED != mobileState) {
            // 手机没有任何的网络
        } else if (wifiState != null && State.CONNECTED == wifiState) {
            // 无线网络连接成功
        }

    }

}

然后,我们需要在应用中注册这个广播,注册广播的方式有两种,①在androidmanifest.xml中注册

<receiver
            android:name="com.test.NetworkBroadcast"
            android:label="NetworkConnection" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
</receiver>

②在java代码中注册,在Activity的OnCreate()方法中注册,在onDestory()方法中卸载

private BroadcastReceiver networkBroadcast=new BroadcastReceiver(); 
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); 
// 设置优先级
filter.setPriority(Integer.MAX_VALUE);
this.registerReceiver(networkBroadcast, filter);

卸载:

if(networkBroadcast != null){
    this.unregisterReceiver(networkBroadcast);
    networkBroadcast=null;
}

③添加权限

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

如果要程序隐藏在后台的话,建议开个service,将BroadcastReceiver注册在service。比如像电话拦截,IP拨号,检测SD卡状态,开机状态等。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。