你如何检查android中的互联网连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2326767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:26:22  来源:igfitidea点击:

How do you check the internet connection in android?

androidandroid-activitynetwork-state

提问by UMAR

I want to check the internet connectivity in each activity. If it is lost a message should be displayed.

我想检查每个活动中的互联网连接。如果丢失,应显示一条消息。

Can any one guide me how to achieve this?

任何人都可以指导我如何实现这一目标吗?

回答by William

Only one connection can be active at any one point. So a simpler answer is:

在任一时刻只能有一个连接处于活动状态。所以更简单的答案是:

final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
    // notify user you are online
} else {
    // notify user you are not online
} 

It also caters for any new type of network such as ConnectivityManager#TYPE_WIMAX

它还适用于任何新型网络,例如 ConnectivityManager#TYPE_WIMAX



Also make sure that you have the required permission to monitor the network state. You need to add this permission to your AndroidManifest.xml:

还要确保您具有监视网络状态所需的权限。您需要将此权限添加到您的 AndroidManifest.xml 中:

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

回答by Dan

You can use the ConnectivityManagerto check the network state.

您可以使用ConnectivityManager来检查网络状态。

ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED 
    || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ) {

    // notify user you are online

}
else if ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED 
    || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) {

    // notify user you are not online
}

Note that the constants ConnectivityManager.TYPE_MOBILE and ConnectivityManager.TYPE_WIFI represent connection types and these two values are not exhaustive. See herefor an exhaustive list.

请注意,常量 ConnectivityManager.TYPE_MOBILE 和 ConnectivityManager.TYPE_WIFI 表示连接类型,这两个值并不详尽。有关详尽列表,请参见此处



Also make sure that you have the required permission to monitor the network state. You need to add this permission to your AndroidManifest.xml:

还要确保您具有监视网络状态所需的权限。您需要将此权限添加到您的 AndroidManifest.xml 中:

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

回答by mainu

You can do this, for various types of network status

您可以针对各种类型的网络状态执行此操作

public void  checkNetworkStatus(){

    final ConnectivityManager connMgr = (ConnectivityManager)
     this.getSystemService(Context.CONNECTIVITY_SERVICE);

     final android.net.NetworkInfo wifi =
     connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

     final android.net.NetworkInfo mobile =
     connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

     if( wifi.isAvailable() ){

     Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show();
     }
     else if( mobile.isAvailable() ){

     Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show();
     }
     else
     {

         Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();
     }

}

回答by Amar Gore

You can check network coverage and data availability of Mobile and wi-fi directly with

您可以直接使用

For Network coverageavailability,

对于网络覆盖可用性,

private boolean isNetworkAvailable()
{
 ConnectivityManager conxMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);

 NetworkInfo mobileNwInfo = conxMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
 NetworkInfo wifiNwInfo   = conxMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

return ((mobileNwInfo== null ? false : mobileNwInfo.isAvailable()) || (wifiNwInfo == null ? false : wifiNwInfo.isAvailable()));

}

For Data availabilityif network available

对于数据的可用性,如果网络可用

private boolean isDataAvailable()
{
  ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

 NetworkInfo mobileNwInfo = conxMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
 NetworkInfo wifiNwInfo   = conxMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

return ((mobileNwInfo== null? false : mobileNwInfo.isConnected() )|| (wifiNwInfo == null? false : wifiNwInfo.isConnected()));
}

回答by Sudhakar Chavali

Correction

更正

if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED 
    ||  conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING  ) {
   //notify user you are online
}

should be

应该

if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED 
    ||  conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
    //notify user you are online
}

回答by caligari

Register a broadcast receiver to handle CONNECTIVITY_ACTION. See this full example. You should update a static variable 'connectionAvailable' that will be accessible everywhere and everytime through its respective getter.

注册一个广播接收器来处理CONNECTIVITY_ACTION。请参阅此完整示例。您应该更新一个静态变量“connectionAvailable”,该变量可以通过其各自的 getter 随时随地访问。

Remember to declare the broadcast receiver in the manifestfile:

请记住在清单文件中声明广播接收器:

<receiver android:name=".NetworkConnectivityReceiver" android:enabled="true">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
</receiver>

On the matter of 'checking in each activity', may be you would be interested in using a BaseActivity extended by your activitiesand managing the test of connectivity and displaying the message.

关于“检查每个活动”的问题,您可能对使用由您的活动扩展BaseActivity以及管理连接测试和显示消息感兴趣。

Also, note that using events(not polling from activities) will be more efficient.

另外,请注意使用事件(不是从活动中轮询)会更有效。

回答by Naskov

You are not using ConnectivityManager.getNetworkInfo(0).getState()and ConnectivityManager.getNetworkInfo(1).getState()properly, instead of hardcoding the values (1) and (0) use ConnectivityManager.TYPE_WIFIand ConnectivityManager.TYPE_MOBILE

您没有正确使用ConnectivityManager.getNetworkInfo(0).getState()ConnectivityManager.getNetworkInfo(1).getState(),而不是硬编码值 (1) 和 (0) 使用ConnectivityManager.TYPE_WIFIConnectivityManager.TYPE_MOBILE

回答by VikingGlen

This is a boolean check to see if you have network access. It doesn't determine what kind of network access - mobile, wifi..., it just checks to see if you're online.

这是一个布尔检查,用于查看您是否具有网络访问权限。它不能确定哪种网络访问 - 移动、wifi...,它只是检查您是否在线。

boolean mobileNwInfo = false;  
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);  
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }  
catch (NullPointerException e) { mobileNwInfo = false; }  
if ( mobileNwInfo == false ) {
  // Your code goes here...
}