检查 Android 上的互联网连接

发布于 2024-09-30 09:59:31 字数 1249 浏览 1 评论 0原文

我有以下代码用于检查我的应用程序上的互联网连接 wifi/EDGE/GPRS/3G。

代码是

public static boolean checkConn(Context ctx) {
    ConnectivityManager conMgr = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {
        return true;
    } else if (conMgr.getNetworkInfo(0).getState()==NetworkInfo.State.DISCONNECTED
        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED){
        return false;
    }
    return false;
}

,我这样称呼它:

if (CheckInternet.checkConn(introPage.this) == true) {
    Intent toMainPage = new Intent(introPage.this, mainPage.class);
    System.gc();
    startActivity(toMainPage);
} else if (CheckInternet.checkConn(getApplicationContext()) == false) {
    Toast.makeText(getApplicationContext(),
        "Sorry, No internet connectivity found", Toast.LENGTH_SHORT)
            .show();
}

但是我遇到了一个问题,那就是如果我连接到wifi,并且我打开应用程序,它工作正常,但是如果我关闭应用程序并关闭wifi并重新-打开应用程序,它不会出现“无连接”错误,我需要关闭设备然后再打开它,同样的情况是如果 wifi 关闭,并且我打开应用程序,它会抛出“无连接”错误”,如果我打开它,它仍然会抛出相同的“无连接”错误,除非我关闭并打开设备。

I have the following code for checking internet connection wifi/EDGE/GPRS/3G on my application.

the code is

public static boolean checkConn(Context ctx) {
    ConnectivityManager conMgr = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {
        return true;
    } else if (conMgr.getNetworkInfo(0).getState()==NetworkInfo.State.DISCONNECTED
        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED){
        return false;
    }
    return false;
}

and I am calling it like below :

if (CheckInternet.checkConn(introPage.this) == true) {
    Intent toMainPage = new Intent(introPage.this, mainPage.class);
    System.gc();
    startActivity(toMainPage);
} else if (CheckInternet.checkConn(getApplicationContext()) == false) {
    Toast.makeText(getApplicationContext(),
        "Sorry, No internet connectivity found", Toast.LENGTH_SHORT)
            .show();
}

But I am having an issue, which is that if I am connected to wifi, and I open the application, it works fine, but if I close application and turn off wifi and re-open application, it doesn't through the error of "no connection" , I need to turn off my device and then turn it on, and same case is if wifi is off, and I open application, it throws error of "no connection", and if I turn it on, still it throws the same error of "no connection", until unless I turn off and on device.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

恍梦境° 2024-10-07 09:59:31

有时活动连接不是列表中的第一个连接,或者处于非活动状态或处于错误状态。我将这样做:

  NetworkInfo i = conMgr.getActiveNetworkInfo();
  if (i == null)
    return false;
  if (!i.isConnected())
    return false;
  if (!i.isAvailable())
    return false;
  return true;

[编辑1]不要忘记在应用程序清单中添加此权限:

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

这对您有帮助吗?

以马内利

Sometimes the active connection is not first in the list, or is inactive or in an error state. This is how I would do it:

  NetworkInfo i = conMgr.getActiveNetworkInfo();
  if (i == null)
    return false;
  if (!i.isConnected())
    return false;
  if (!i.isAvailable())
    return false;
  return true;

[EDIT 1] Don't forget to add this permission in the application manifest:

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

Does this help you?

Emmanuel

坏尐絯 2024-10-07 09:59:31

简短的回答:

public boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getApplicationContext()
                                              .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

The short answer:

public boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getApplicationContext()
                                              .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}
箜明 2024-10-07 09:59:31

更好:

if (conMgr != null) {
    NetworkInfo i = conMgr.getActiveNetworkInfo();
    if (i != null) {
        if (!i.isConnected())
            ret = false;
        if (!i.isAvailable())
            ret = false;                
    }

    if (i == null)
        ret = false;

} else
    ret = false;

使用另一种形式,如果“Network i”等于 null,则检查 !i.isConnected() 必须失败(i 为 null)。

Is better:

if (conMgr != null) {
    NetworkInfo i = conMgr.getActiveNetworkInfo();
    if (i != null) {
        if (!i.isConnected())
            ret = false;
        if (!i.isAvailable())
            ret = false;                
    }

    if (i == null)
        ret = false;

} else
    ret = false;

with the other form, if "Network i" is equal null then, check after for !i.isConnected() must fail (i is null).

我喜欢麦丽素 2024-10-07 09:59:31
public static boolean checkNetworkStatus(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    TelephonyManager telephony = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    NetworkStatus netStatus = new NetworkStatus(connectivity, telephony);
    if (netStatus.isNetworkAvailable() == true) {
        Log.e(" in checkNetworkStatus()", "network available");
        return true;
    } else {
        Log.e(" in checkNetworkStatus()", "no network");
        return false;
    }
}

无线上网-


void chkStatus() {
    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();
    }
}
public static boolean checkNetworkStatus(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    TelephonyManager telephony = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    NetworkStatus netStatus = new NetworkStatus(connectivity, telephony);
    if (netStatus.isNetworkAvailable() == true) {
        Log.e(" in checkNetworkStatus()", "network available");
        return true;
    } else {
        Log.e(" in checkNetworkStatus()", "no network");
        return false;
    }
}

wifi-


void chkStatus() {
    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();
    }
}
成熟稳重的好男人 2024-10-07 09:59:31

试试这个:

public boolean isInternetAvailable(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo i = conMgr.getActiveNetworkInfo();
          if (i == null)
            return false;
          if (!i.isConnected())
            return false;
          if (!i.isAvailable())
            return false;
          return true;

    }

这个权限:

Try this:

public boolean isInternetAvailable(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo i = conMgr.getActiveNetworkInfo();
          if (i == null)
            return false;
          if (!i.isConnected())
            return false;
          if (!i.isAvailable())
            return false;
          return true;

    }

and this permission:

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

我是男神闪亮亮 2024-10-07 09:59:31

您好,尝试以下代码:

   public class NetworkCheckDemo extends Activity
 {
TextView tvstatus;
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tvstatus=(TextView)findViewById(R.id.txtviewstatus);
    ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf=cn.getActiveNetworkInfo();
    if(nf != null && nf.isConnected()==true )
    {
        Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("Network Available");
    }
    else
    {
        Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("Network Not Available");
      }
    }
  }

在 Android Manifest 文件中添加以下 3 个权限。

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

Hi try the following code :

   public class NetworkCheckDemo extends Activity
 {
TextView tvstatus;
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tvstatus=(TextView)findViewById(R.id.txtviewstatus);
    ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf=cn.getActiveNetworkInfo();
    if(nf != null && nf.isConnected()==true )
    {
        Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("Network Available");
    }
    else
    {
        Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("Network Not Available");
      }
    }
  }

Add below 3 permissions in Android Manifest File.

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
素衣风尘叹 2024-10-07 09:59:31

我曾经检查是否有连接,不要忘记检查 NetworkInfo 是否为 null,因为在不提供移动数据连接的平板电脑上,TYPE_MOBILE 的 NetworkInfo 返回 null。

public static boolean collectionAllowed(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(
            ConnectivityManager.TYPE_MOBILE);
    State mobile = NetworkInfo.State.DISCONNECTED;
    if ( mobileInfo != null) {
        mobile = mobileInfo.getState();
    }
    NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(
            ConnectivityManager.TYPE_WIFI);
    State wifi = NetworkInfo.State.DISCONNECTED;
    if ( wifiInfo != null) {
        wifi = wifiInfo.getState();
    }
    boolean dataOnWifiOnly = (Boolean) PreferenceManager
            .getDefaultSharedPreferences(context).getBoolean(
                    "data_wifi_only", true);
    if ((!dataOnWifiOnly && (mobile.equals(NetworkInfo.State.CONNECTED) || wifi
            .equals(NetworkInfo.State.CONNECTED)))
            || (dataOnWifiOnly && wifi.equals(NetworkInfo.State.CONNECTED))) {
        return true;
    } else {
        return false;
    }
}

I used to check if I have connectivity, don't forget to check if the NetworkInfo is null or not because on tablet where mobile data connectivity is not provided, the NetworkInfo for TYPE_MOBILE return null.

public static boolean collectionAllowed(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(
            ConnectivityManager.TYPE_MOBILE);
    State mobile = NetworkInfo.State.DISCONNECTED;
    if ( mobileInfo != null) {
        mobile = mobileInfo.getState();
    }
    NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(
            ConnectivityManager.TYPE_WIFI);
    State wifi = NetworkInfo.State.DISCONNECTED;
    if ( wifiInfo != null) {
        wifi = wifiInfo.getState();
    }
    boolean dataOnWifiOnly = (Boolean) PreferenceManager
            .getDefaultSharedPreferences(context).getBoolean(
                    "data_wifi_only", true);
    if ((!dataOnWifiOnly && (mobile.equals(NetworkInfo.State.CONNECTED) || wifi
            .equals(NetworkInfo.State.CONNECTED)))
            || (dataOnWifiOnly && wifi.equals(NetworkInfo.State.CONNECTED))) {
        return true;
    } else {
        return false;
    }
}
但可醉心 2024-10-07 09:59:31

与批准的答案相同,但简而言之:

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return info != null && info.isConnected() && info.isAvailable();
}

same as the approved answer but in short :

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return info != null && info.isConnected() && info.isAvailable();
}
溺渁∝ 2024-10-07 09:59:31

您可以使用这个很棒的 emil2k 的要点

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

public class Connectivity {
    public static NetworkInfo getNetworkInfo(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    public static boolean isConnected(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected());
    }

    public static boolean isConnectedWifi(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
    }

    public static boolean isConnectedMobile(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    public static boolean isConnectedFast(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(),info.getSubtype()));
    }

    public static boolean isConnectionFast(int type, int subType){
        if(type==ConnectivityManager.TYPE_WIFI){
            return true;
        }else if(type==ConnectivityManager.TYPE_MOBILE){
            switch(subType){
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            /*
             * Above API level 7, make sure to set android:targetSdkVersion 
             * to appropriate level to use these
             */
            case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
                return false; // ~25 kbps 
            case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
                return true; // ~ 10+ Mbps
            // Unknown
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            default:
                return false;
            }
        }else{
            return false;
        }
    }

}

You can use this awesome gist by emil2k :

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

public class Connectivity {
    public static NetworkInfo getNetworkInfo(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    public static boolean isConnected(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected());
    }

    public static boolean isConnectedWifi(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
    }

    public static boolean isConnectedMobile(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    public static boolean isConnectedFast(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(),info.getSubtype()));
    }

    public static boolean isConnectionFast(int type, int subType){
        if(type==ConnectivityManager.TYPE_WIFI){
            return true;
        }else if(type==ConnectivityManager.TYPE_MOBILE){
            switch(subType){
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            /*
             * Above API level 7, make sure to set android:targetSdkVersion 
             * to appropriate level to use these
             */
            case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
                return false; // ~25 kbps 
            case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
                return true; // ~ 10+ Mbps
            // Unknown
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            default:
                return false;
            }
        }else{
            return false;
        }
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文