连接网络上的活动Internet连接

时间:2018-05-24 18:29:18

标签: android android-studio networking wifi network-state

我的应用程序活动是有一段代码,我想在访问FireBase Auth Login之前检查已连接的网络是否有活动连接。

我为 networkState 创建了一个类,添加了一个代码块来检查 networkActiveConnection

private void networkState() throws IOException {

    final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    assert conMgr != null;
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {

        Toast.makeText(getApplicationContext(),"Network connected",Toast.LENGTH_SHORT).show();

        //checking active internet service

        HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(10000);
        urlc.connect();
        if(urlc.getResponseCode() == 200){

            Toast.makeText(getApplicationContext(), "Network has active internet", Toast.LENGTH_SHORT).show();

            //user login

            signInUser();

        }else {

            Toast.makeText(getApplicationContext(), "No active internet connection", Toast.LENGTH_SHORT).show();
        }

        //end of checking active internet service

    } else {

        Toast.makeText(getApplicationContext(),"Network not connected",Toast.LENGTH_SHORT).show();

    }
}

应用程序不断崩溃。没有解决方案,我无法移动。我错过了什么?有没有其他方法可以检查连接的网络是否有活动连接?

1 个答案:

答案 0 :(得分:0)

最后我找到了答案。它实际上是由于版本而发生的。在Android 3.0及更高版本中,所有长时间的流程活动仅适用于AsyncTask

我通过Google.com的加载检查重新构建了设备中的实际互联网连接。我不知道当google.com关闭时会发生什么。

以下代码可能有所帮助。

@SuppressLint("StaticFieldLeak")
public class activeConnection extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {

        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(3000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            }
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onPostExecute(Boolean result) {
        if (!result) { // code if not connected

            AlertDialog.Builder builder = new AlertDialog.Builder(Customers.this, R.style.MyDialogTheme);
            builder.setTitle("ALERT");
            builder.setMessage("Activate your Internet connection and Try again");
            builder.setCancelable(false);

            builder.setPositiveButton(
                    "Retry",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                            new activeConnection().execute();
                        }
                    });


            AlertDialog alert11 = builder.create();
            alert11.show();
        } else { // code if connected


        }
    }
}