判断网络连接情况

判断网络连接情况
 
// 判断网络连接情况,利用广播
boolean isNetWorkOk=false; 【这里将网络状态连接情况保存在isNetWorkOk,其他地方要使用直接利用该布尔值判断就可以了
class MyNetWork extends BroadcastReceiver
{
    @Override
    public void onReceive ( Context context, Intent intent)
    {
        myNetState(context, intent);
    }
}
    public void myNetState ( Context context, Intent intent)
    {
        // intent.putExtras(bundle1);
        Bundle bundle = intent.getExtras();
        NetworkInfo networkInfo = (NetworkInfo) bundle.get(ConnectivityManager.EXTRA_NETWORK_INFO);
        // networkInfo.isConnected()是否连接
        // networkInfo.isAvailable()是否有效
       if (networkInfo.isConnected() && networkInfo.isAvailable())
        {
            // 连接成功后的业务逻辑
            // 具体的网络连接方式
            switch (networkInfo.getType())
            {
            case ConnectivityManager.TYPE_WIFI:
            case ConnectivityManager.TYPE_MOBILE:
            // 执行业务,连接成功
            isNetWorkOk = true;
            break;
            default:
            isNetWorkOk = false;
            break;
            }
        }
        else
        {
            // 断网的业务逻辑
            isNetWorkOk = false;
        }
    }
// 注册广播
myNetWork = new MyNetWork();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(myNetWork, intentFilter);
// 注销广播
this.unregisterReceiver(myNetWork);
posted on 2013-10-26 16:02  知行立远  阅读(243)  评论(0编辑  收藏  举报