266

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

附件是我到目前为止的代码,但我收到了错误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();
            }
        }
    }
4

20 回答 20

479

此方法检查手机是否已连接到互联网,如果已连接则返回 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;
    }
}
于 2012-03-05T16:34:51.003 回答
100

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

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

于 2013-04-20T20:35:36.173 回答
74

您可以简单地 ping 一个在线网站,例如 google:

public boolean isConnected() throws InterruptedException, IOException {
    String command = "ping -c 1 google.com";
    return Runtime.getRuntime().exec(command).waitFor() == 0;
}
于 2015-12-09T10:03:17.247 回答
36

当您连接到 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 或任何其他方法中。把它放在一个类中并访问它。

于 2014-02-06T05:48:23.677 回答
28

您可以使用以下代码段来检查 Internet 连接。

您可以检查哪种网络连接类型可用,这样您就可以按照这种方式进行处理,这两种方式都很有用。

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

/**
 * @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" />

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

谢谢你。

于 2015-10-21T10:04:58.273 回答
24

接受的答案的 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("");
}
于 2015-12-16T19:48:27.143 回答
14

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

于 2012-03-05T16:32:50.943 回答
14

所有官方方法只告诉设备是否打开网络,
如果您的设备连接到 Wifi 但 Wifi 未连接到互联网,那么这些方法将失败(这种情况发生很多次),没有内置的网络检测方法会告诉这个场景,因此创建了将在onConnectionSuccessonConnectionFail中返回的异步回调类

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;
    }
}
于 2015-11-17T18:23:54.903 回答
9

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

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

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

您还需要:

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

在你的 android 清单中。

有关更多详细信息,请转到此处

于 2014-07-11T07:56:19.107 回答
7

使用此方法:

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" />
于 2015-12-19T15:39:49.343 回答
5

试试下面的代码:

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;
    }
于 2012-03-05T16:58:01.383 回答
4

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
}
于 2014-08-30T23:41:35.650 回答
3
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;
}
于 2014-01-22T05:16:50.410 回答
3

在清单中

<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;
}
于 2014-12-30T07:59:14.617 回答
3

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

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;
        }
于 2015-03-17T12:29:13.780 回答
2

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

于 2013-05-28T13:09:53.337 回答
2

这是我在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);

于 2014-05-22T05:15:55.183 回答
1

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

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();

    }
}
于 2014-08-08T06:49:59.083 回答
1

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

如何在手机中检查 WIFI 和 3G(数据计划)中的网络连接启用或禁用?

于 2014-12-20T21:24:16.577 回答
1

在具有互联网数据速度的 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" />
于 2015-04-15T07:25:33.003 回答