Android check connection without context
i would like to kno开发者_如何学编程w 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
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.
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;
}
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();
精彩评论