【问题标题】:Android check internet connection [duplicate]Android检查互联网连接[重复]
【发布时间】:2012-03-23 03:16:57
【问题描述】:

我想创建一个使用互联网的应用程序,并且我正在尝试创建一个函数来检查连接是否可用,如果不可用,请转到具有重试按钮和说明的活动。

到目前为止,附件是我的代码,但我收到错误 Syntax error, insert "}" to complete MethodBody.

现在我一直在尝试让它工作,但到目前为止没有运气......任何帮助将不胜感激。

public class TheEvoStikLeagueActivity extends Activity {
    private final int SPLASH_DISPLAY_LENGHT = 3000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        private boolean checkInternetConnection() {
            ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
            // ARE WE CONNECTED TO THE NET
            if (conMgr.getActiveNetworkInfo() != null
                    && conMgr.getActiveNetworkInfo().isAvailable()
                    && conMgr.getActiveNetworkInfo().isConnected()) {

                return true;

                /* New Handler to start the Menu-Activity
                 * and close this Splash-Screen after some seconds.*/
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        /* Create an Intent that will start the Menu-Activity. */
                        Intent mainIntent = new Intent(TheEvoStikLeagueActivity.this, IntroActivity.class);
                        TheEvoStikLeagueActivity.this.startActivity(mainIntent);
                        TheEvoStikLeagueActivity.this.finish();
                    }
                }, SPLASH_DISPLAY_LENGHT);
            } else {
                return false;

                Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this, HomeActivity.class);
                TheEvoStikLeagueActivity.this.startActivity(connectionIntent);
                TheEvoStikLeagueActivity.this.finish();
            }
        }
    }

【问题讨论】:

标签: android networking android-networking


【解决方案1】:

此方法检查手机是否已连接到互联网,如果已连接则返回 true:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}

在清单中,

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

编辑: 这个方法实际上检查设备是否连接到互联网(有可能它连接到网络但没有连接到互联网)。

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com"); 
        //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
    }
}

【讨论】:

  • 这个答案不正确。如果您连接到不路由到 Internet 的网络,此方法将错误地返回 true。请注意,getActiveNetworkInfo 的 javadoc 说您应该检查 NetworkInfo.isConnected(),但这也不足以检查您是否在 Internet 上。我正在进一步调查,但您可能需要 ping 互联网上的服务器以确保您确实在互联网上。
  • 它是否也检查 3G、EDGE、GPRS 等?
  • 请注意 isInternetAvailable(),因为它可能会在“主线程上的网络”异常中失败,因此即使您有连接也会返回 false。
  • isInternetAvailable() 总是为我返回 false。即使绕过捕获。我在使用 3G。
  • 第一部分在主线程中起作用,第二部分(编辑)仅在不在主线程中起作用。
【解决方案2】:

检查以确保它已“连接”到网络:

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}

检查以确保它已“连接”到互联网:

public boolean isInternetAvailable() {
    try {
        InetAddress address = InetAddress.getByName("www.google.com");
        return !address.equals("");
    } catch (UnknownHostException e) {
        // Log error
    }
    return false;
}

需要许可:

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

https://stackoverflow.com/a/17583324/950427

【讨论】:

  • 如何查找,已连接到 wifi 但实际上没有 wifi 上的活动数据。
  • 仅告诉您是否连接到网络,而不是互联网。如果您想要崩溃(对于互联网安全代码),请使用它。
  • 这与接受的答案有何不同?
  • @SeshuVinay 阅读日期。我在 4 年前发布了这个。
  • 我的测试设备似乎缓存了 Google 服务器的 IP,所以 isInternetAvailable 总是为我返回 true。使用不同的服务器会起作用,但这样做不是很可靠。我可以对缓存做些什么吗?
【解决方案3】:

您可以简单地 ping 诸如 google 之类的在线网站:

public boolean isConnected() throws InterruptedException, IOException {
    String command = "ping -c 1 google.com";
    return Runtime.getRuntime().exec(command).waitFor() == 0;
}

【讨论】:

  • 好的,但不是最好的。整个逻辑取决于 google.com 让我们假设如果谷歌关闭了几分钟,那么你的应用将在几分钟内无法工作
  • 那你有什么建议?
  • 好吧,@ZeeshanShabbir 是对的,对于 google 主要业务所在国家/地区的太阳耀斑会使您的应用程序直接退出球场,在这种情况下,您可以适当地 ping 到几个地址检查相同。另外,我认为如果一个中心宕机,谷歌不会宕机,如果你的网络运营商在全球停电中幸存下来,他们中的大部分必须被关闭才能正常工作:D
  • 如果您的应用程序依赖于远程服务器(用于身份验证、获取数据、与数据库通信......等),那么您可以使用该服务器地址而不是 google,这样您就可以检查互联网连接性和服务器可用性。如果您的服务器已关闭并且仍然有互联网连接,则该应用程序无论如何都无法正常运行。在这种情况下,您可能还想使用 -i 选项设置 ping 命令的超时间隔,例如 ping -i 5 -c 1 www.myserver.com
  • 这个方法在有wifi登录页面的场景下会不会错误返回true?
【解决方案4】:

当您连接到 Wi-Fi 源或通过手机数据包时,上述方法有效。但是在 Wi-Fi 连接的情况下,有时会进一步要求您像在咖啡厅一样登录。因此,在这种情况下,您的应用程序将失败,因为您连接到 Wi-Fi 源但未连接到 Internet。

这个方法很好用。

    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }

    return false;

}

请在与主线程不同的线程中使用它,因为它会进行网络调用,如果不遵循将抛出 NetwrokOnMainThreadException。

并且也不要将此方法放在 onCreate 或任何其他方法中。将它放在一个类中并访问它。

【讨论】:

  • 这是解决问题的好方法。但可能一个 ping 就足够了
  • 当您只需要简单地检查互联网响应时,线程带来的困难是不值得的。 Ping 毫不费力地完成了这项工作。
  • 最佳方法(期间)。套接字、InetAddress 方法很容易出错,特别是当您的设备连接到没有互联网连接的 Wifi 网络时,它会继续指示互联网是可访问的,即使它不是。
【解决方案5】:

您可以使用以下 sn-p 来检查 Internet 连接。

这两种方式都很有用,您可以检查哪个类型 NETWORK 连接可用,因此您可以通过这种方式进行处理。

您只需复制以下类并直接粘贴到您的包中。

/**
 * @author Pratik Butani
 */
public class InternetConnection {

    /**
     * CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT
     */
    public static boolean checkConnection(Context context) {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connMgr != null) {
            NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

            if (activeNetworkInfo != null) { // connected to the internet
                // connected to the mobile provider's data plan
                if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    // connected to wifi
                    return true;
                } else return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
            }
        }
        return false;
    }
}

现在你可以像这样使用:

if (InternetConnection.checkConnection(context)) {
    // Its Available...
} else {
    // Not Available...
}

不要忘记获得许可 :) :)

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

您可以根据自己的要求进行修改。

谢谢。

【讨论】:

  • android.permission.ACCESS_WIFI_STATE 这里不需要。
  • 您正在检查设备当前是否连接了 wifi 网络或蜂窝网络。例如,当设备连接到无法访问互联网的 wifi 网络时,这种方式是不够的。
【解决方案6】:

接受的答案的 EDIT 显示了如何检查是否可以访问 Internet 上的某些内容。如果不是这种情况(使用没有互联网连接的 wifi),我不得不等待太久才能得到答案。不幸的是 InetAddress.getByName 没有超时参数,所以下一个代码可以解决这个问题:

private boolean internetConnectionAvailable(int timeOut) {
    InetAddress inetAddress = null;
    try {
        Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
            @Override
            public InetAddress call() {
                try {
                    return InetAddress.getByName("google.com");
                } catch (UnknownHostException e) {
                    return null;
                }
            }
        });
        inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
        future.cancel(true);
    } catch (InterruptedException e) {
    } catch (ExecutionException e) {
    } catch (TimeoutException e) {
    } 
    return inetAddress!=null && !inetAddress.equals("");
}

【讨论】:

  • 这对于我不必管理“可达性”状态的一次奇怪检查来说效果很好。
  • 即使我连接到互联网,此方法也会返回 false。有什么想法吗?
  • 这应该是公认的答案。
  • InetAddress.equals() 的源代码设置为始终返回 false (Android 30) 不得不求助于 tostring 然后等于
【解决方案7】:

您不能在另一个方法中创建方法,请将private boolean checkInternetConnection() { 方法移出onCreate

【讨论】:

  • 您可以创建一个线程来连续查找网络可用性并让您知道并在间隔后继续重试。
【解决方案8】:

所有官方方法只告诉设备是否开放网络,
如果您的设备连接到 Wifi 但 Wifi 未连接到互联网,那么这些方法将失败(这种情况发生很多次),没有内置的网络检测方法会告诉这种情况,因此创建了 Async Callback 类,它将在 onConnectionSuccess 和 onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

    @Override
    public void onConnectionSuccess() {
        Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFail(String msg) {
        Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
    }
}).execute();

来自异步任务的网络调用

public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > {
    private OnConnectionCallback onConnectionCallback;
    private Context context;

    public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
        super();
        this.onConnectionCallback = onConnectionCallback;
        this.context = con;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void...params) {
        if (context == null)
            return false;

        boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
        return isConnected;
    }

    @Override
    protected void onPostExecute(Boolean b) {
        super.onPostExecute(b);

        if (b) {
            onConnectionCallback.onConnectionSuccess();
        } else {
            String msg = "No Internet Connection";
            if (context == null)
                msg = "Context is null";
            onConnectionCallback.onConnectionFail(msg);
        }

    }

    public interface OnConnectionCallback {
        void onConnectionSuccess();

        void onConnectionFail(String errorMsg);
    }
}

将 ping 到服务器的实际类

class NetWorkInfoUtility {

    public boolean isWifiEnable() {
        return isWifiEnable;
    }

    public void setIsWifiEnable(boolean isWifiEnable) {
        this.isWifiEnable = isWifiEnable;
    }

    public boolean isMobileNetworkAvailable() {
        return isMobileNetworkAvailable;
    }

    public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
        this.isMobileNetworkAvailable = isMobileNetworkAvailable;
    }

    private boolean isWifiEnable = false;
    private boolean isMobileNetworkAvailable = false;

    public boolean isNetWorkAvailableNow(Context context) {
        boolean isNetworkAvailable = false;

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
        setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

        if (isWifiEnable() || isMobileNetworkAvailable()) {
            /*Sometime wifi is connected but service provider never connected to internet
            so cross check one more time*/
            if (isOnline())
                isNetworkAvailable = true;
        }

        return isNetworkAvailable;
    }

    public boolean isOnline() {
        /*Just to check Time delay*/
        long t = Calendar.getInstance().getTimeInMillis();

        Runtime runtime = Runtime.getRuntime();
        try {
            /*Pinging to Google server*/
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            long t2 = Calendar.getInstance().getTimeInMillis();
            Log.i("NetWork check Time", (t2 - t) + "");
        }
        return false;
    }
}

【讨论】:

  • 请注意Runtime据我所知只能在有根的应​​用程序中使用
  • 我找到的最佳解决方案,它可以在您连接到 wifi 网络或手机数据时检测互联网是否可用
  • 很遗憾,某些三星设备不允许 Ping。
【解决方案9】:

无需复杂。最简单和框架的方式是使用ACCESS_NETWORK_STATE权限,只做一个连接方法

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

如果您有特定的主机和连接类型(wifi/移动),您也可以使用requestRouteToHost

您还需要:

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

在您的 android 清单中。

更多详情go here

【讨论】:

【解决方案10】:

使用这个方法:

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

这是所需的权限:

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

【讨论】:

  • 使用非 Internet 路由连接重复且不准确地返回 true
【解决方案11】:

试试下面的代码:

public static boolean isNetworkAvailable(Context context) {
        boolean outcome = false;

        if (context != null) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo[] networkInfos = cm.getAllNetworkInfo();

            for (NetworkInfo tempNetworkInfo : networkInfos) {


                /**
                 * Can also check if the user is in roaming
                 */
                if (tempNetworkInfo.isConnected()) {
                    outcome = true;
                    break;
                }
            }
        }

        return outcome;
    }

【讨论】:

  • 这是我到目前为止所得到的 private boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni == null) { // 没有活动网络。 Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this,InfoActivity.class); TheEvoStikLeagueActivity.this.startActivity(connectionIntent); EvoStikLeagueActivity.this.finish();返回假; } 否则返回真; }
  • 请尝试我发布的代码来检查设备是否可以连接到远程服务器...
【解决方案12】:

1-创建新的java文件(右键单击包。新建>类>将文件命名为ConnectionDetector.java

2-将以下代码添加到文件中

package <add you package name> example com.example.example;

import android.content.Context;
import android.net.ConnectivityManager;

public class ConnectionDetector {

    private Context mContext;

    public ConnectionDetector(Context context){
        this.mContext = context;
    }

    public boolean isConnectingToInternet(){

        ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() == true)
        {
            return true; 
        }

        return false;

    }
}

3- 打开您的MainActivity.java - 您要检查连接的活动,然后执行以下操作

A- 创建和定义函数。

ConnectionDetector mConnectionDetector;</pre>

B-在“OnCreate”里面添加如下

mConnectionDetector = new ConnectionDetector(getApplicationContext());

c- 使用以下步骤检查连接

if (mConnectionDetector.isConnectingToInternet() == false) {
//no connection- do something
} else {
//there is connection
}

【讨论】:

    【解决方案13】:
    public boolean checkInternetConnection(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } 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;
    }
    

    【讨论】:

      【解决方案14】:

      在清单中

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

      在代码中,

      public static boolean isOnline(Context ctx) {
          if (ctx == null)
              return false;
      
          ConnectivityManager cm =
                  (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo netInfo = cm.getActiveNetworkInfo();
          if (netInfo != null && netInfo.isConnectedOrConnecting()) {
              return true;
          }
          return false;
      }
      

      【讨论】:

      • android.permission.ACCESS_WIFI_STATE 这里不需要。
      【解决方案15】:

      使用此代码检查互联网连接

      ConnectivityManager connectivityManager = (ConnectivityManager) ctx
                      .getSystemService(Context.CONNECTIVITY_SERVICE);
              if ((connectivityManager
                      .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
                      .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
                      || (connectivityManager
                              .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                              .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                              .getState() == NetworkInfo.State.CONNECTED)) {
                  return true;
              } else {
                  return false;
              }
      

      【讨论】:

        【解决方案16】:

        在“return”语句之后,你不能写任何代码(不包括try-finally块)。 将新的活动代码移到“return”语句之前。

        【讨论】:

          【解决方案17】:

          这是我作为Utils 类的一部分使用的函数:

          public static boolean isNetworkConnected(Context context) {
              ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
              return (cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isConnectedOrConnecting();
          }
          

          像这样使用它:Utils.isNetworkConnected(MainActivity.this);

          【讨论】:

          • 假设网络仍在连接是否安全?
          • 取决于您的用例...
          【解决方案18】:

          我对 IsInternetAvailable 答案不测试蜂窝网络有问题,而仅在连接了 wifi 时才测试。此答案适用于 wifi 和移动数据:

          How to check network connection enable or disable in WIFI and 3G(data plan) in mobile?

          【讨论】:

            【解决方案19】:

            这是处理所有情况的另一种选择:

            public void isNetworkAvailable() {
                ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                } else {
                    Toast.makeText(ctx, "Internet Connection Is Required", Toast.LENGTH_LONG).show();
            
                }
            }
            

            【讨论】:

            • ctx 是必须是全局的上下文。
            • 是的,你是对的!我们需要将它定义为一个全局变量
            【解决方案20】:

            检查网络在 android 中是否可用,具有互联网数据速度。

            public boolean isConnectingToInternet(){
                    ConnectivityManager connectivity = (ConnectivityManager) Login_Page.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                      if (connectivity != null)
                      {
                          NetworkInfo[] info = connectivity.getAllNetworkInfo();
                          if (info != null)
                              for (int i = 0; i < info.length; i++)
                                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                                  {
                                      try
                                        {
                                            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                                            urlc.setRequestProperty("User-Agent", "Test");
                                            urlc.setRequestProperty("Connection", "close");
                                            urlc.setConnectTimeout(500); //choose your own timeframe
                                            urlc.setReadTimeout(500); //choose your own timeframe
                                            urlc.connect();
                                            int networkcode2 = urlc.getResponseCode();
                                            return (urlc.getResponseCode() == 200);
                                        } catch (IOException e)
                                        {
                                            return (false);  //connectivity exists, but no internet.
                                        }
                                  }
            
                      }
                      return false;
                }
            

            此函数返回真或假。 必须获得用户许可

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

            【讨论】:

              猜你喜欢
              • 2017-11-30
              • 1970-01-01
              • 1970-01-01
              • 2012-06-12
              • 1970-01-01
              • 2013-08-16
              • 2016-08-28
              • 1970-01-01
              • 2014-02-18
              相关资源
              最近更新 更多