小编典典

Android检查互联网连接

all

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

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

阅读 68

收藏
2022-05-13

共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;
    }
}
2022-05-13