Android 判断网络状态及开启网路
来源:爱站网时间:2019-10-31编辑:网友分享
android在连接网络时,并不是每次能够连接到网络,有时候也会出现连接不了的情况,我们最好在程序启动时判断网络的状态,下面是爱站技术频道小编带来的Android 判断网络状态及开启网路,希望能让大家有所收获!
android在连接网络时,并不是每次能够连接到网络,有时候也会出现连接不了的情况,我们最好在程序启动时判断网络的状态,下面是爱站技术频道小编带来的Android 判断网络状态及开启网路,希望能让大家有所收获!
Android 判断网络状态及开启网路
要判断网络状态,首先需要有相应的权限,下面为权限代码:
即允许访问网络状态:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
下面为判断代码:
/**
* 测试网络
*/
public boolean TestNetWork()
{
if(context != null){
ConnectivityManager connectivityManager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetInfo==null){
handler.sendEmptyMessage(8);
return false;
}
boolean netInfo = activeNetInfo.isAvailable();
if(!netInfo){
handler.sendEmptyMessage(8);
return false;
}
}
return true;
}
上文就是关于Android 判断网络状态及开启网路,阅读之外相信大家有了一定的了解,我们每天定时更新许多的Android资讯,喜欢的朋友可以收藏爱站技术频道!
