Gerardo
Gerardo

Reputation: 5830

Android check connection without context

i would like to know if it's possible check connectivity in android without having a Context, because the thread i have running in background doesn't know the context. if there's no way, is a best practice passing to the thread the context?

thanks

Upvotes: 5

Views: 3365

Answers (3)

Rahul
Rahul

Reputation: 641

you can use this below method

Kotlin :

fun isNetworkAvailable1(): Boolean {
        val runtime = Runtime.getRuntime()
        try {
            val ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8")
            val exitValue = ipProcess.waitFor()
            return exitValue == 0
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
        return false
    }

Java :

public static boolean isNetworkAvailable () {
    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;
}

Upvotes: 1

skyman
skyman

Reputation: 2472

Your runnable Object will run inside Activity or Service so it will have access to its methods

I think you can simply do:

OuterClassName.this.getContext();

Upvotes: -1

CommonsWare
CommonsWare

Reputation: 1006704

Yes, you need the Context. Possibly, your thread will already have access to a Context, courtesy of the Runnable it uses being an inner class of the Activity or Service that forked the thread.

Upvotes: 4

Related Questions