Search code examples
androidandroid-studionetwork-programmingwifinetwork-state

Active Internet Connection on connected network


My application activity is having a block of code which I want to check the connected network having active connection before accessing FireBase Auth Login.

I created a class for networkState add a block of code for checking 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();

    }
}

Application keeps crashing. I cant move without the solution.Where I missed? Is there any other method to check the connected network having active connection?


Solution

  • Finally I found an answer.Its actually happening due to the version. Up to Android 3.0 and above all long process activities will work at only AsyncTask

    I restructured the actual internet connection in the device by load checking of Google.com. I don't know what it will happen when google.com is down.

    The following code may help.

    @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
    
    
            }
        }
    }