在开发过程中,尤其是在开发网络应用的时候,时常要判断手机的联网状态,及时的给用户友善的提示。我们登录market,在网络断开的时候会及时的弹出警告窗口,避免用户盲目的等待。
这样的判断要贯穿在整个应用当中,在用户切换Activity,或者是后台service运行的时候都可能要用到。所以我们可以将判断的逻辑封装成一个方法,让其他Activity/service公用。
public static boolean isNetworkAvailable( Activity mActivity ) {
Context context = mActivity.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
/**
* 检测网络是否存在
*/
public static void HttpTest(final Activity mActivity)
{
if( !isNetworkAvailable( mActivity) ){
AlertDialog.Builder builders = new AlertDialog.Builder(mActivity);
builders.setTitle(“抱歉,暂时无法处理您的请求”);
LayoutInflater _inflater = LayoutInflater.from(mActivity);
View convertView = _inflater.inflate(R.layout.error,null);
builders.setView(convertView);
builders.setPositiveButton(“确定”, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
mActivity.finish();
}
});
builders.show();
}
}
备注:别忘记在mainfest.xml中添加
android.permission.ACCESS_NETWORK_STATE
权限