我想创建一个使用互联网的应用程序,我试图创建一个功能,检查连接是否可用,如果它不是,去到一个活动,有一个重试按钮和解释。

附件是我的代码到目前为止,但我得到的错误语法错误,插入“}”来完成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();
            }
        }
    }

当前回答

当您连接到Wi-Fi源或通过手机数据包时,上述方法都有效。但在Wi-Fi连接的情况下,有时你会被进一步要求登录,就像在咖啡馆一样。所以在这种情况下,你的应用程序将失败,因为你连接的是Wi-Fi源,而不是互联网。

这个方法很有效。

    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;

}

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

也不要把这个方法放在onCreate或任何其他方法中。把它放到一个类中并访问它。

其他回答

检查网络可用在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;
    }

此函数返回true或false。 必须获得用户权限

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

下面是一个函数,我使用作为我的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);

使用这个方法:

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

当您连接到Wi-Fi源或通过手机数据包时,上述方法都有效。但在Wi-Fi连接的情况下,有时你会被进一步要求登录,就像在咖啡馆一样。所以在这种情况下,你的应用程序将失败,因为你连接的是Wi-Fi源,而不是互联网。

这个方法很有效。

    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;

}

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

也不要把这个方法放在onCreate或任何其他方法中。把它放到一个类中并访问它。

这是处理所有情况的另一个选项:

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

    }
}