javaandroidserverping

Android - Check internet connection by pinging url address


I need a service in the background that constantly pings google. But I have no idea how to do it. I am new here. My method does not work does not repeat. It only works once and it always returns "false" .

isConnectedToServer function

 public boolean isConnectedToServer(String url, int timeout) {
try{
  URL myUrl = new URL(url);
  URLConnection connection = myUrl.openConnection();
  connection.setConnectTimeout(timeout);
  connection.connect();
  return true;
} catch (Exception e) {
  // Handle your exceptions
  return false;
}}

onCreate

     @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 if(isConnectedToServer("http://www.google.com",3000)){
      Toast.makeText(this, "Okay", Toast.LENGTH_SHORT).show();
    }else{
      Toast.makeText(this, "Not Okay", Toast.LENGTH_SHORT).show();
    }}

Manifest

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

I see Not Okay once on the screen. Only once. Even when I have an internet connection. What can I do about it?


Solution

  • try this create a class that extends AsyncTask

    public class CheckInternet extends AsyncTask<Void, Void, Boolean>{
     private static final String TAG = "CheckInternet";
    private Context context;
    
    
    public CheckInternet(Context context) {
        this.context = context;
    
    }
    
    @Override
    protected Boolean doInBackground(Void... voids) {
        Log.d(TAG, "doInBackground: ");
        ConnectivityManager cm =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    
        assert cm != null;
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnected();
    
        if (isConnected) {
            if ( executeCommand()) return true;
        }
        return false;
    }
    
    private boolean executeCommand(){
        System.out.println("executeCommand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c "+"www.google.com");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue "+mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }
        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;
    }