- <strong>public?class?NetworkDetector?{??
- ???
- ????public?static?boolean?detect(Activity?act)?{??
- ????????
- ???????ConnectivityManager?manager?=?(ConnectivityManager)?act??
- ??????????????.getApplicationContext().getSystemService(??
- ?????????????????????Context.CONNECTIVITY_SERVICE);??
- ????????
- ???????if?(manager?==?null)?{??
- ???????????return?false;??
- ???????}??
- ????????
- ???????NetworkInfo?networkinfo?=?manager.getActiveNetworkInfo();??
- ????????
- ???????if?(networkinfo?==?null?||?!networkinfo.isAvailable())?{??
- ???????????return?false;??
- ???????}??
- ???
- ???????return?true;??
- ????}??
- }</strong>??
?
?
?
这个类只有一个静态方法,用来检测当前系统的网络是否可用。如果可用,返回true。
还要进一步说明的是,NetworkInfo类中有一个方法getType(),这个方法可以用来判断当前可用的网络是wifi,还是mobile等等。
?
再来看使用的例子。
?
?
- boolean?networkState?=?NetworkDetector.detect(XXXActivity.this);??
- if?(!networkState)?{??
- ????DialogUtil.openMsgDialog(XXXActivity.this,??
- ???????????android.R.drawable.ic_dialog_info,??
- ???????????“网络不可用,是否现在设置网络?”,?android.R.string.ok,??
- ???????????android.R.string.cancel,??
- ???????????new?DialogInterface.OnClickListener()?{??
- ??????????????@Override??
- ??????????????public?void?onClick(DialogInterface?dialog,?int?which)?{??
- ??????????????????startActivityForResult(new?Intent(??
- ?????????????????????????ACTION_WIRELESS_SETTINGS),?0);??
- ??????????????}??
- ???????????},?new?DialogInterface.OnClickListener()?{??
- ??????????????@Override??
- ??????????????public?void?onClick(DialogInterface?dialog,?int?which)?{??
- ??????????????????dialog.cancel();??
- ??????????????}??
- ???????????}).show();??
- }??
?
?
?
其中XXXActivity是我自己的Activity类,DialogUtil是我自己定义的Dialog应用类。这里的代码片段,是在判断没有网络的情况下,弹出dialog,提示用户是否进入系统的网络设置界面。
?
因为以上代码用到了权限,需要在AndroidManifest文件中加入如下权限代码:
????<uses-permission
???????android:name="android.permission.ACCESS_NETWORK_STATE"?/>