其实浏览器的网络监听和处理不过是通知给WebView进行, 没有那么多复杂的操作, 使用了NetworkStateHandler这个类来进行处理
在Controller中初始化这个类
mNetworkHandler = new NetworkStateHandler(mActivity, this); //网络变化监听
/** * Handle network state changes * 处理网络变化 */public class NetworkStateHandler { Activity mActivity; Controller mController; // monitor platform changes private IntentFilter mNetworkStateChangedFilter; private BroadcastReceiver mNetworkStateIntentReceiver; private boolean mIsNetworkUp; public NetworkStateHandler(Activity activity, Controller controller) { mActivity = activity; mController = controller; // Find out if the network is currently up. ConnectivityManager cm = (ConnectivityManager) mActivity .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null) { mIsNetworkUp = info.isAvailable(); //是否可以连接网络 } /* * enables registration for changes in network status from http stack * 网络变化监听的filter 和receiver */ mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { NetworkInfo info = intent.getParcelableExtra( ConnectivityManager.EXTRA_NETWORK_INFO); String typeName = info.getTypeName(); //获取网络类型是wifi还是mobile String subtypeName = info.getSubtypeName();//hspa 之类 sendNetworkType(typeName.toLowerCase(), (subtypeName != null ? subtypeName.toLowerCase() : "")); //网络是否连通 boolean noConnection = intent.getBooleanExtra( ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); onNetworkToggle(!noConnection); } } }; } void onPause() { //在pause中解注册 // unregister network state listener mActivity.unregisterReceiver(mNetworkStateIntentReceiver); } void onResume() {//在resume中注册 mActivity.registerReceiver(mNetworkStateIntentReceiver, mNetworkStateChangedFilter); } /** * connectivity manager says net has come or gone... inform the user * @param up true if net has come up, false if net has gone down */ void onNetworkToggle(boolean up) { if (up == mIsNetworkUp) { return; } mIsNetworkUp = up; WebView w = mController.getCurrentWebView(); if (w != null) { w.setNetworkAvailable(up);//告诉webview 网络是否可以联通 } } boolean isNetworkUp() { return mIsNetworkUp; } private void sendNetworkType(String type, String subtype) { WebView w = mController.getCurrentWebView(); if (w != null) { //通知内核当前的网络信息 w.setNetworkType(type, subtype); } }}
至此浏览器的分析基本上就结束了, 当然也不是特别全面, 回头看去, 也积累了很多东西, 多看代码, 每天积累一些, 对发展是又好处的.