Android 检查网络状态

samool 发布1 条评论16689 阅读

AI摘要

本文介绍了在Android开发中如何检查网络状态。首先,需要在程序中添加访问网络状态的权限。然后,通过ConnectivityManager类和getActiveNetworkInfo()方法来获取网络信息,并判断网络是否可用。如果网络不可用,可以弹出对话框提示用户进行网络设置。最后,提供了一个完整的代码示例来展示如何实现网络状态的检查和用户提示。

在使用Android连接网络的时候,并不是每次都能连接到网络,在这个时候,我们最好是在程序启动的时候对网络的状态进行一下判断,如果没有网络则进行即时提醒用户进行设置。

要判断网络状态,首先需要有相应的权限,下面为权限代码:

即允许访问网络状态:

 

<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

privatebooleanNetWorkStatus() {

booleannetSataus=false;
ConnectivityManager cwjManager
=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

cwjManager.getActiveNetworkInfo();

if(cwjManager.getActiveNetworkInfo()!=null) {
netSataus
=cwjManager.getActiveNetworkInfo().isAvailable();
}

if(netSataus) {
Builder b
=newAlertDialog.Builder(this).setTitle("没有可用的网络")
.setMessage(
"是否对网络进行设置?");
b.setPositiveButton(
"是",newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog,intwhichButton) {
Intent mIntent
=newIntent("/");
ComponentName comp
=newComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
mIntent.setComponent(comp);
mIntent.setAction(
"android.intent.action.VIEW");
startActivityForResult(mIntent,
0);//如果在设置完成后需要再次进行操作,可以重写操作代码,在这里不再重写
}
}).setNeutralButton(
"否",newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog,intwhichButton) {
dialog.cancel();
}
}).show();
}

returnnetSataus;
}

 通过上面的代码即可完成对网络状态的判断!

  1. 01android平台获取手机IMSI、IMEI 、序列号和手机号的方法2016-01-07
  2. 02Android TextView添加滚动条2014-05-09
  3. 03Android TextView换行问题2014-03-25
  4. 04android 删除文件2013-07-26
  5. 05android bitmap的放大缩小2013-07-26
  6. 06Android MediaPlayer使用方法2013-02-16
  7. 07Android软件图标的几种大小2013-01-07
  8. 08谷歌发布Android 4.2系统2012-10-30
  9. 09Android 4.1.2源码今天将发布2012-10-10
  10. 10Android打开系统设置界面 2012-04-12
COMMENTS / 一纸留言

读者留言 1 条

一纸留言,便是山水间的一次相逢。

  1. pan pan

    以上代码在2.X系统下运行没问题,但是在3.X或者4.0下运行崩溃

WRITE A COMMENT

写下你的留言