---
title: "Android判断是否有可用网络的代码"
author: "mars5337"
date: "2010-08-29T11:52:02Z"
tags: ["Android", "网络应用"]
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2010-08-29T11:52:02Z"
id: 750021
url: "https://mars5337.iteye.com/blog/750021"
---

在开发基于网络的应用的时候，需要判断是否有可用的网络，如果没有开启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。