ConnectionManager是负责网路管理的类。
获取ConnectivityManager
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
获取可用的NetworkInfo()
NetworkInfo info = manager.getActiveNetworkInfo();
获取wifi和移动网络的信息
NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
判断网路是否连接
wifiInfo.isConnected();
public class ConnectChangeReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectChangeReceiver";
/**
* 获取ConnectivityManager
* 获取ConnectionInfo
* 判断网络是否可用
*/
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifiInfo.isConnected() || mobileInfo.isConnected()) {
Log.d(TAG, "联网正常");
} else {
Log.d(TAG, "联网失败");
}
}
}
}
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
ConnectChangeReceiver receiver = new ConnectChangeReceiver();
registerReceiver(receiver, filter);
unregisterReceiver(receiver);