简体   繁体   中英

Check Android's Internet Connection in a Background Thread

I am trying to check if there is an active internet connection, and after searching, I found a working code answered by Levit:

https://stackoverflow.com/a/27312494/2920212

This seems to work fine except sometimes, it causes a lag where it appears like the app is frozen. I know its because the isOnline function is not run in a background thread. I have searched but unable to implement the background thread properly. Please find below the code:

    public boolean isOnline() {

    Runtime runtime = Runtime.getRuntime();
    try {

        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

Here is what I've tried:

    private void ChecOnline() {
    class CheckURL extends AsyncTask<Void, Void, Boolean> {


        @Override
        protected Boolean doInBackground(Void... params) {
            return isOnline();

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            String myresult = Boolean.toString(result);
            Toast.makeText(getApplicationContext(), myresult, Toast.LENGTH_LONG).show();
        }
    }
    CheckURL ucc = new CheckURL();
    ucc.execute();

Nothing happens when ChecOnline(); is called.

Try it using AsyncTask

private class CheckOnlineStatus extends AsyncTask<Void, Integer, Boolean> {


    @Override
    protected Boolean doInBackground(Void... params) {
        //This is a background thread, when it finishes executing will return the result from your function.
        Boolean isOnline = isOnline();
        return isOnline;
    }

    protected void onPostExecute(Boolean result) {
    //Here you will receive your result from doInBackground
    //This is on the UI Thread
    }
}

Then you will call

new CheckOnlineStatus().execute();

to execute your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM