Android 判断网络状态这一应用技巧在实际应中是比较重要的。那么,在Android操作系统中,如何能够正确的判断我们所连接的网络是否断开恩?今天我们就针对这一应用技巧进行一个详细的分析。
<!-- Needed to check when the network connection changes -->
另一种方法:
//注册一个广播接收者,接收网络连接状态改变广播
public class ConnectionChangeReceiver extends BroadcastReceiver {
@Override
public 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) {
Toast.makeText(context,
"Active Network Type : " + activeNetInfo.getTypeName(),
Toast.LENGTH_SHORT).show();
}
if (mobNetInfo != null) {
Toast.makeText(context,
"Mobile Network Type : " + mobNetInfo.getTypeName(),
Toast.LENGTH_SHORT).show();
}
}
}
<!-- Needed to check when the network connection changes -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<receiver
android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
另一种方法:
public boolean isNetworkAvailable() {
Context context = getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
boitealerte(this.getString(R.string.alert),
"getSystemService rend null");
} else {//获取所有网络连接信息
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {//逐一查找状态为已连接的网络
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
本文介绍两种在Android中检查网络状态的方法。一种是通过广播接收器监听网络连接变化,并展示活动网络和移动网络类型。另一种是直接检查当前是否有可用的网络连接。
998

被折叠的 条评论
为什么被折叠?



