标签:
在开发android应用时,涉及到要进行网络访问,时常需要进行网络状态的检查,以提供给用户必要的提醒。一般可以通过ConnectivityManager来完成该工作。
ConnectivityManager有四个主要任务:
1、监听手机网络状态(包括GPRS,WIFI, UMTS等)
2、手机状态发生改变时,发送广播
3、当一个网络连接失败时进行故障切换
4、为应用程序提供可以获取可用网络的高精度和粗糙的状态
当我们要在程序中监听网络状态时,只要一下几个步骤即可:
1、处理Recevier接口
package com.gense.ips.main.receiver; import java.util.Map; /** * * 广播接收器处理接口 * * @author J.Wang * @version [版本号, 2015年4月29日] * @see [相关类/方法] * @since [产品/模块版本] */ public interface ReceiverHandler { public void handlerReceiver(int receiverType,Map<String,Object> param ); }
2、定义一个Receiver重载其中的onReceive函数,在其中完成所需要的功能,如根据WIFI和GPRS是否断开来改变空间的外观或者提示是否能访问网络
package com.gense.ips.main.receiver; import java.util.HashMap; import java.util.Map; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * @author J.Wang * */ public class ConnectionChangeReceiver extends BroadcastReceiver { public static String NET_CONENCT_STATUS = "net_conenct_status"; public static int RECEIVER_TYPE = 100010; //广播接收处理器 private ReceiverHandler receiverHandler; public ConnectionChangeReceiver(ReceiverHandler receiverHandler) { this.receiverHandler = receiverHandler; } @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); Map<String ,Object> params = new HashMap<String ,Object>(); if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) { //改变背景或者 处理网络的全局变量 params.put(NET_CONENCT_STATUS, "false"); }else { //改变背景或者 处理网络的全局变量 params.put(NET_CONENCT_STATUS, "true"); } this.receiverHandler.handlerReceiver(RECEIVER_TYPE,params); } }
3、注册Receiver,可以在程序中注册,
/** * 注册Receiver * @see [类、类#方法、类#成员] */ protected void _registerReceiver(BroadcastReceiver broadcastReceiver) { IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); this.registerReceiver(broadcastReceiver, filter); }
4、取消注册Receiver
/** * 取消注册Receiver * @param broadcastReceiver * @see [类、类#方法、类#成员] */ protected void _unregisterReceiver(BroadcastReceiver broadcastReceiver) { this.unregisterReceiver(broadcastReceiver); }
5、Receiver程序处理
/** * 处理系统广播事件 * @param param */ public void handlerReceiver(int receiverType,Map<String, Object> param) { //处理网络连接通知 if(receiverType == ConnectionChangeReceiver.RECEIVER_TYPE) { String isConnect = StringUtils.get(param, ConnectionChangeReceiver.NET_CONENCT_STATUS); if("true".equals(isConnect)) { HttpTask task = new HttpTask(this, Constants.LOGIN_LOAD_PARAMETERS); task.execute(); } else { this.showShortMessage("网络未连接"); } } }
标签:
原文地址:http://www.cnblogs.com/wangjuneng/p/4466013.html