ITeye博客

Android判断是否有可用网络的代码

mars5337 · 2010-08-29 11:52 · 移动开发 · 网络应用 · Android · Markdown

在开发基于网络的应用的时候,需要判断是否有可用的网络,如果没有开启WIFI或者APN的话,是无法连接网络的。以下代码是判断是否有网络,以及没有网络的话,打开系统设置进行开启。

private boolean CheckNetwork() { boolean flag = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (cwjManager.getActiveNetworkInfo() != null) flag = cwjManager.getActiveNetworkInfo().isAvailable(); if (!flag) { Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage(getResources().getString("请开启GPRS或WIFI网络连接")); b.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent mIntent = new Intent("/"); ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"); mIntent.setComponent(comp); mIntent.setAction("android.intent.action.VIEW"); startActivity(mIntent); } }).setNeutralButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }).create(); b.show(); }

	return flag;
}

主要是通过Intent来调用开启网络的Activity。

评论(1)

  1. #1 楼 · zxciop1100 · 2012-07-13 12:00

    没用 在定制机中直接报错 没有网络的状态下 开启配置界面就会报错 垃圾华为+电信

评论功能维护中,当前仅展示历史评论。