精华内容
参与话题
问答
  • NetWorkInfo

    2012-10-01 09:53:19
    获取主机名和ip,方便大家学习有关网络编程的基础知识。
  • NetworkInfo

    2016-05-30 21:31:54
    获取网络信息需要在AndroidManifest.xml文件中加入相应的权限。 1)判断是否有网络连接 [java] view plain copy  print? public boolean isNetworkConnected(Context context) { ... 

    获取网络信息需要在AndroidManifest.xml文件中加入相应的权限。

    1)判断是否有网络连接

    [java] view plain copy
     print?
    1. public boolean isNetworkConnected(Context context) {  
    2.     if (context != null) {  
    3.         ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
    4.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
    5.         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();  
    6.         if (mNetworkInfo != null) {  
    7.             return mNetworkInfo.isAvailable();  
    8.         }  
    9.     }  
    10.     return false;  
    11. }  


     

    2)判断WIFI网络是否可用

    [java] view plain copy
     print?
    1. public boolean isWifiConnected(Context context) {  
    2.     if (context != null) {  
    3.         ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
    4.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
    5.         NetworkInfo mWiFiNetworkInfo = mConnectivityManager  
    6.                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI);  
    7.         if (mWiFiNetworkInfo != null) {  
    8.             return mWiFiNetworkInfo.isAvailable();  
    9.         }  
    10.     }  
    11.     return false;  
    12. }  

    3)判断MOBILE网络是否可用

    [java] view plain copy
     print?
    1. public boolean isMobileConnected(Context context) {  
    2.     if (context != null) {  
    3.         ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
    4.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
    5.         NetworkInfo mMobileNetworkInfo = mConnectivityManager  
    6.                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);  
    7.         if (mMobileNetworkInfo != null) {  
    8.             return mMobileNetworkInfo.isAvailable();  
    9.         }  
    10.     }  
    11.     return false;  
    12. }  


     4)获取当前网络连接的类型信息

    [java] view plain copy
     print?
    1. public static int getConnectedType(Context context) {  
    2.     if (context != null) {  
    3.         ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
    4.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
    5.         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();  
    6.         if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {  
    7.             return mNetworkInfo.getType();  
    8.         }  
    9.     }  
    10.     return -1;  
    11. }  


     

    展开全文
  • By default the Docker executor publishes the IP of the Docker container into the NetworkInfo field. Unfortunately, unless you're running some kind of SDN solution, bridged, or host networking ...
  • NetworkInfoNetworkInfo.State(四)

    千次阅读 2015-11-14 10:58:53
    NetworkInfo这个类主要是描述网络连接的信息,由ConnectivityManager 类的方法调用获得。 NetworkInfo.State getState() Reports the current coarse-grained state of the network. NetworkInfo.State 详细信息...

    转载请标明出处:http://blog.csdn.net/xx326664162/article/details/49386533 文章出自:薛瑄的博客

    你也可以查看我的其他同类文章,也会让你有一定的收货!

    关于Android WiFi,我写了5篇文章,讲解了在配置WiFi中用到的知识

    WifiManager、ScanResult(一)
    WifiInfo(二)
    ConnectivityManager(三)
    NetworkInfo和NetworkInfo.State(四)
    WifiManager、WifiInfo、WifiConfiguration集成类(五)

    NetworkInfo

    这个类主要是描述网络连接的信息,由ConnectivityManager 类的方法调用获得。
    NetworkInfo.State getState()
    Reports the current coarse-grained state of the network.

    NetworkInfo.State

    详细信息Detailed state 粗粒度Coarse-grained state
    IDLE DISCONNECTED
    SCANNING CONNECTING
    CONNECTING CONNECTING
    AUTHENTICATING CONNECTING
    CONNECTED CONNECTED
    DISCONNECTING DISCONNECTING
    DISCONNECTED DISCONNECTED
    UNAVAILABLE DISCONNECTED
    FAILED DISCONNECTED

    关注我的公众号,轻松了解和学习更多技术
    这里写图片描述

    展开全文
  • Add NetworkInfo Singleton

    2020-12-26 14:43:43
    <div><p>NetworkInfo will contain a collection of NetworkAdapters The ability to programmatically configure adapters (including wireless) will be exposed by this API</p><p>该提问来源于开源项目:...
  • getNetworkInfo

    千次阅读 2016-08-23 13:30:21
    我们一般通过connectivityManager 来检测当前是否有wifi或则mobile 连接。 如下所示: ConnectivityManager connMgr = (ConnectivityManager)  getSystemService(Context....NetworkInfo networkInfo = connM
    我们一般通过connectivityManager 来检测当前是否有wifi或则mobile 连接。
    如下所示:
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    boolean isWifiConn = networkInfo.isConnected();
    我们来看看ConnectivityManager的getNetworkInfo 实现


    xref: /frameworks/base/core/java/android/net/ConnectivityManager.java
    739    public NetworkInfo getNetworkInfo(Network network) {
    740        try {
    741            return mService.getNetworkInfoForNetwork(network);
    742        } catch (RemoteException e) {
    743            return null;
    744        }
    745    }


    其中mService的赋值
    1485    private INetworkManagementService getNetworkManagementService() {
    1486        synchronized (this) {
    1487            if (mNMService != null) {
    1488                return mNMService;
    1489            }
    1490            IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
    1491            mNMService = INetworkManagementService.Stub.asInterface(b);
    1492            return mNMService;
    1493        }
    1494    }


    可以看出ConnectivityManager是通过binder调用到ConnectivityService的getNetworkInfoForNetwork
    xref: /frameworks/base/services/core/java/com/android/server/ConnectivityService.java
    1048    @Override
    1049    public NetworkInfo getNetworkInfoForNetwork(Network network) {
    1050        enforceAccessPermission();
    1051        final int uid = Binder.getCallingUid();
    1052        NetworkInfo info = null;
    1053        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
    1054        if (nai != null) {
    1055            synchronized (nai) {
    1056                info = new NetworkInfo(nai.networkInfo);
    1057                info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
    1058            }
    1059        }
    1060        return info;
    1061    }




    1050行check是否ACCESS_NETWORK_STATE 权限,这也是为什么我们要在manifest文件中定义ACCESS_NETWORK_STATE
    1443    private void enforceAccessPermission() {
    1444        mContext.enforceCallingOrSelfPermission(
    1445                android.Manifest.permission.ACCESS_NETWORK_STATE,
    1446                "ConnectivityService");
    1447    }


    在getNetworkInfoForNetwork 中先调用getNetworkAgentInfoForNetwork 获取NetworkAgentInfo
    876    private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
    877        if (network == null) {
    878            return null;
    879        }
    880        synchronized (mNetworkForNetId) {
    881            return mNetworkForNetId.get(network.netId);
    882        }
    883    };


    881行是mNetworkForNetId 是一个数组,所以我们是根据网络类型在这个数组中找info,那什么时候往这个数组中添加数据呢?
    3871    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
    3872            new SparseArray<NetworkAgentInfo>();


    可以看到是在handleRegisterNetworkAgent 中调用put函数
    3920    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
    3921        if (VDBG) log("Got NetworkAgent Messenger");
    3922        mNetworkAgentInfos.put(na.messenger, na);
    3923        synchronized (mNetworkForNetId) {
    3924            mNetworkForNetId.put(na.network.netId, na);
    3925        }
    3926        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
    3927        NetworkInfo networkInfo = na.networkInfo;
    3928        na.networkInfo = null;
    3929        updateNetworkInfo(na, networkInfo);
    3930    }


    而handleRegisterNetworkAgent 又是在处理EVENT_REGISTER_NETWORK_AGENT 也就是在注册网络类型的时候调用的。
       private class InternalHandler extends Handler {
    2477        public InternalHandler(Looper looper) {
    2478            super(looper);
    2479        }
    2480
    2481        @Override
    2482        public void handleMessage(Message msg) {
    2483            switch (msg.what) {


    2525                case EVENT_REGISTER_NETWORK_AGENT: {
    2526                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
    2527                    break;
    2528                }
    而InternalHandler是在ConnectivityService的构造函数中新建的,所以ConnectivityService是会处理 EVENT_REGISTER_NETWORK_AGENT 来添加网络类型.
    625    public ConnectivityService(Context context, INetworkManagementService netManager,
    626            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
    627        if (DBG) log("ConnectivityService starting up");


    640        mHandler = new InternalHandler(mHandlerThread.getLooper());




    回到ConnectivityService的getNetworkInfoForNetwork函数中
    如果已经注册这个类型,则在getNetworkInfoForNetwork的1056行new 一个NetworkInfo 用于返回
     public NetworkInfo(NetworkInfo source) {
    148        if (source != null) {
    149            synchronized (source) {
    150                mNetworkType = source.mNetworkType;
    151                mSubtype = source.mSubtype;
    152                mTypeName = source.mTypeName;
    153                mSubtypeName = source.mSubtypeName;
    154                mState = source.mState;
    155                mDetailedState = source.mDetailedState;
    156                mReason = source.mReason;
    157                mExtraInfo = source.mExtraInfo;
    158                mIsFailover = source.mIsFailover;
    159                mIsRoaming = source.mIsRoaming;
    160                mIsAvailable = source.mIsAvailable;
    161            }
    162        }
    163    }
    NetworkInfo的构造函数如上所示,注意的是这里154行会赋值mState = source.mState而我们调用的isConnected也是在NetworkInfo 这个class中实现的
    251    public boolean isConnected() {
    252        synchronized (this) {
    253            return mState == State.CONNECTED;
    254        }
    255    }
    展开全文
  • NetworkInfo已过时

    千次阅读 2020-04-16 15:50:43
    今天编译的时候发现网络请求前,用于判断是否通畅的函数提示警告,内容为NetworkInfo过时 赶紧点开查看过时说明,发现API level 29该类过时,ConnectivityManager中返回值为NetworkInfo的方法一并不推荐使用了。 @...

    今天编译的时候发现,请求网络前判断设备是否联网的方法提示警告,内容为NetworkInfo过时
    赶紧点开查看过时说明,发现NetworkInfo在API level 29中过时,ConnectivityManager中有许多返回值为NetworkInfo的方法,自此一并不推荐使用了。
    以前我们常用mConnectivityManager.getActiveNetworkInfo()获取NetworkInfo,通过isConnected()判断是否连通
    查阅文档显示如下

    @deprecated Callers should instead use the {@link ConnectivityManager.NetworkCallback} API to
     *             learn about connectivity changes, or switch to use
     *             {@link ConnectivityManager#getNetworkCapabilities} or
     *             {@link ConnectivityManager#getLinkProperties} to get information synchronously. Keep
     *             in mind that while callbacks are guaranteed to be called for every event in order,
     *             synchronous calls have no such constraints, and as such it is unadvisable to use the
     *             synchronous methods inside the callbacks as they will often not offer a view of
     *             networking that is consistent (that is: they may return a past or a future state with
     *             respect to the event being processed by the callback). Instead, callers are advised
     *             to only use the arguments of the callbacks, possibly memorizing the specific bits of
     *             information they need to keep from one callback to another.
    

    官方提到了两个同步方法,和一个异步方法,官方警告说同步的方法会有更新不及时,反馈不及时的问题,无法保证多次调用的结果一致性。
    但我主要为了判断瞬时网络通断,就使用返回NetworkCapabilities的getNetworkCapabilities

    1)网络状态改变监听:异步方法ConnectivityManager.NetworkCallback (NetWork)
    2)网络状态获取:同步方法
    //获取网络属性
    public NetworkCapabilities getNetworkCapabilities (@Nullable Network network)
    方法内部调用的是:mService.getNetworkCapabilities(network);
    //获取连接属性
    public LinkProperties getLinkProperties(int networkType) 
        public LinkProperties getLinkProperties(@Nullable Network network)
    方法内部调用的是:mService.getLinkPropertiesForType(networkType);
    
    //注意 上述两个方法的Network是通过mConnectivityManager.getActiveNetwork()获取的
    

    官方推荐的替代方案中使用的NetworkCapabilities,是API 21增加的类,但API23中才增加了判断的描述NET_CAPABILITY_VALIDATED,因此NetworkCapabilities最低支持Android 6.0版本.
    实际使用时需要做版本判断,项目如需兼容早期版本则无法完全摒除NetworkInfo
    参考帖子了中对NetworkCapabilities的测试,发现其描述中有“VALIDATED”字段时,此网络是真正可用的。

    打印networkCapabilities.toString()
    
    未联网
    networkCapabilities=null
    
    移动4G流量
    NetworkCapalbilities:[ Transports: CELLULAR Capabilities: SUPL&INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN&VALIDATED&NOT_ROAMING&FOREGROUND&NOT_CONGESTED&NOT_SUSPENDED Unwanted:  LinkUpBandwidth>=51200Kbps LinkDnBandwidth>=102400Kbps Specifier: <1>]
    
    wifi
    5G热点
    NetworkCapalbilities:[ Transports: WIFI Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN&VALIDATED&NOT_ROAMING&FOREGROUND&NOT_CONGESTED&NOT_SUSPENDED Unwanted:  LinkUpBandwidth>=1048576Kbps LinkDnBandwidth>=1048576Kbps SignalStrength: -46]
    4G热点
    NetworkCapalbilities:[ Transports: WIFI Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN&VALIDATED LinkUpBandwidth>=1048576Kbps LinkDnBandwidth>=1048576Kbps SignalStrength: -53]
    
    本次只用了热点wifi做测试,但已经看出来4G和5G有一些差别
    

    结合参考文档中测试的两种情况
    1)在不可上网的wifi下,可以看到也没有VALIDATED的标记
    在不可上网的wifi下,可以看到也没有VALIDATED的标记
    2)在需要认证的wifi下,可以看到相应区域没有VALIDATED的标记
    在需要认证的wifi下,可以看到相应区域没有VALIDATED的标记
    综合上述信息,NetworkCapabilities的描述中有VALIDATED这个描述时,此网络是真正可用的。那么我们可以:

    1)通过判断这个标记是否存在来判断网络的连通性
    networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
    2)通过字符串转义抓取判断
    networkCapabilities.toString().indexOf("VALIDATED") > -1;
    

    综合以上情况修改网络判断代码如下:

    public static boolean isConnected() {
    	ConnectivityManager mConnectivityManager = (ConnectivityManager) BaseApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    	if(Build.VERSION.SDK_INT>=23) {
    		//获取网络属性
    		NetworkCapabilities networkCapabilities = mConnectivityManager.getNetworkCapabilities(mConnectivityManager.getActiveNetwork());
    		if (networkCapabilities != null) {
    			LogUtil.i("Avalible","NetworkCapalbilities:"+networkCapabilities.toString());
    			return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
    		}
    	}else {
    		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    		if (mNetworkInfo != null) {
    			return mNetworkInfo.isConnected();
    		}
    	}
    	return false;
    }
    
    展开全文
  • android10解决NetworkInfo废弃替代NetworkInfo isConnected()问题 最近新项目接近尾声,进入处理疑难杂症阶段;着手处理各种兼容性问题。在监听系统网络广播变化方面遇到了一个问题,在Android 10 (系统sdk...
  • networkinfo.csv Header

    2021-01-11 01:16:27
    <div><p>can I have header for all column in <code>networkinfo.csv</code> file please. thanks.</p><p>该提问来源于开源项目:mgp25/Chat-API</p></div>
  • add Created to NetworkInfo

    2020-11-29 12:40:02
    <div><p>This PR adds <code>Created()</code> to the <code>NetworkInfo</code> interface and <code>created</code> to the <code>network</code> structure for implementation of ...<p>Signed-off-by: Akihiro ...
  • <div><p>In MESOS-3788, the NetworkInfo message was updated to clarify the structure of how IPs map onto interfaces. <p>Update mesos-dns to use the new NetworkInfo.</p><p>该提问来源于开源项目:...
  • android 解决getNetworkInfo过时

    万次阅读 2018-04-26 08:39:04
    今天,简单讲讲android里如何解决getNetworkInfo过时的问题。 之前,我写了一篇博客,讲如何获取手机是否连网,其中有的代码用到了ConnectivityManager 的getNetworkInfo函数,但是最近检查代码时,发现get...
  • s no space/subnet found for it when returning NetworkInfo <h2>QA steps <p>Launch landscape- tests on spaceless envs (GCE, Rackspace) <h2>Documentation changes <p>None. <h2>Bug reference <p>...
  • NetworkInfo 方法过时的处理方法

    千次阅读 2020-04-20 18:58:36
    android 5.0之后把NetworkInfo 标记过时了,它的方法基本都标记过时了 但是目前仍然可以使用,我们可以使用Network 来代替来写网络标识的判断 简单的写一个网络判断 不要忘记在配置文件里面填写权限,不然会包错 ...
  • <div><p>Since API 28 all NetworkInfo properties are deprecated https://developer.android.com/reference/android/net/NetworkInfo and it is intended not to use them but use <code>NetworkCallback</code> ...
  • API之NetworkInfo解释

    千次阅读 2016-06-27 00:17:51
    API之NetworkInfo解释
  • <div><p>Can i get NetworkInfo's typeName and subtypeName like WIFI?</p><p>该提问来源于开源项目:pwittchen/ReactiveNetwork</p></div>
  • <div><p>Some customers use the MAC Address returned from <a href="https://qz.io/api/qz.websocket#.getNetworkInfo"><code>getNetworkInfo</code></a> as a way to assist with their own internal product ...
  • <div><p>The response of the <code>GetNetworkInfo</code> RPC contains the following fields: <pre><code>proto message NetworkInfo { uint32 graph_diameter = 1; double avg_out_degree = 2; uint...
  • <p>getnetworkinfo appears to not exist in the clearnet branch. If I switch back to master and build in the same way, it works fine. <h2>Your Environment <p>Ubuntu 16.04</p><p>该提问来源于开源项目ÿ...
  • react native NetWorkInfo.getSSID怎么使用,放在conponentwillmount里报错,说不是一个有效的function,请大神们教教我
  • m on bitcoin testnet and I get this error message when trying to use getnetworkinfo. <pre><code> ~ lncli getnetworkinfo unable to decode response: json: unsupported value: NaN </code></pre>该提问来源...
  • Where previously Mesos-DNS picked up the values of some special labels appended to a task status, Mesos 0.25.0 introduces a new structure called <code>NetworkInfo</code>. <h2>Change summary <p>This ...
  • ConnectivityManager和NetworkInfo详解

    千次阅读 2015-10-14 16:38:48
    Android网络编程(二)ConnectivityManager和NetworkInfo详解 分类: Android开发 2014-12-04 14:27 2153人阅读 评论(0) 收藏 举报 Android网络编程ConnectivityManagerNetworkInfo  一. ...
  • Device Device模块管理设备信息,用于获取手机设备的相关信息,如IMEI、...对象: networkinfo networkinfo模块用于获取网络信息 networkinfo 常量 CONNECTION_UNKNOW: 网络连接状态未知 CONNECTION_NONE: 未连接...
  • <p>The array <code>NetworkInfo.Portgroup</code> starts as <code>host.Config.Network.Portgroup</code> (containing Management Network & VM Network). It is updated when port groups are added or ...
  • <div><p>[NetworkInfo] Signal strength query returned error: Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied", descriptor: <CTServiceDescriptor 0x10f228680, domain=1, ...

空空如也

1 2 3 4 5 ... 20
收藏数 1,248
精华内容 499
关键字:

networkinfo