android 监测 程序,Android之监测手机网络状态的广播

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

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

网络状态切换的广播类:

packagecom.test;

importandroid.content.BroadcastReceiver;

importandroid.content.Context;

importandroid.content.Intent;

importandroid.net.ConnectivityManager;

importandroid.net.NetworkInfo.State;

publicclassextendsBroadcastReceiver {

@Override

publicvoidonReceive(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) {

// 手机网络连接成功

} elseif(wifiState !=null&& mobileState !=null

&& State.CONNECTED != wifiState

&& State.CONNECTED != mobileState) {

// 手机没有任何的网络

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

// 无线网络连接成功

}

}

}

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

第一种:

android:name="com.test.NetworkBroadcast"

android:label="NetworkConnection">

第二种:

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

privateBroadcastReceiver networkBroadcast=newBroadcastReceiver();

privatevoidregisterNetworkReceiver() {

IntentFilter filter = newIntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);

this.registerReceiver(networkBroadcast, filter);

}

privatevoidunRegisterNetworkReceiver() {

this.unregisterReceiver(networkBroadcast);

}

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值