android 判断是否有可用网络
?
?
方法一:
private boolean NetWorkStatus() {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(("请开启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;}
?
方法二:
?
public class ConnNetworkCheckUtils extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);if (activeNetInfo != null) {// 有网络,可以进行下一步操作,一般进入软件应用} else {Dialog dialog = new AlertDialog.Builder(xuchiLBS.this).setTitle("网络异常")// 设置标题.setMessage((String) "没有找到可用网络,请确认WIFI、3G、2G至少一项可以使用!")// 设置内容.setPositiveButton("确定",// 设置确定按钮new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int whichButton) {dialog.cancel();xuchiLBS.this.finish();}}).create();// 创建按钮// 显示对话框dialog.show();}}}
还要加入权限
? ? ? ? <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
? ? ? ? <receiver android:name="activity所在的全包名" android:label="NetworkConnection">
? ? ? ? ? ? ? ? <intent-filter>
? ? ? ? ? ? ? ? ? ? ? ? <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
? ? ? ? ? ? ? ? </intent-filter>
? ? ? ? </receiver>