Issue
i need help in this kotlin code pls ... i have checkConnctivvity() function and it's working perfectly ...
fun checkConnectivity(){
val cm=getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork =cm.activeNetworkInfo
val isConnected=activeNetwork != null && activeNetwork.isConnectedOrConnecting}
1/ i tried different ways to call it from other activities but i couldn't ... How to solve it plz
2/ i want to add the checkConnectivity() function in webChromeClient , so each time the progressBarChanged it will verify the connection .. but didn't worked
class ExodyaActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_exodya)
//Problem1: failed to call the checkConnectivity() from MainActivity
val myWebview = ExoWeb
var ProgressBar = progressBar
var FrameLayout = frameLayout
var TextView = loadPrs
myWebview.visibility = View.GONE
frameLayout.visibility = View.GONE
loadLinear.visibility = View.GONE
//webview
myWebview.webViewClient= WebViewClient()
myWebview.settings.javaScriptEnabled=true
myWebview.loadUrl("url")
ProgressBar.max = 100
myWebview.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, progress: Int) {
// Problem2: checkConnectivity() didn't work here !!!!
progressBar.progress = progress
if(progress < 90) {
loadPrs.text = " %" + progress
myWebview.visibility = View.GONE
frameLayout.visibility = View.VISIBLE
loadLinear.visibility = View.VISIBLE
}
if (progress == 100) {
FrameLayout.visibility = View.GONE
loadLinear.visibility = View.GONE
myWebview.visibility = View.VISIBLE
}
}
}
}
// onBackPressed (back in webview history)
override fun onBackPressed() {
var myWebview = ExoWeb
if (myWebview.canGoBack()) {
myWebview.goBack()
} else {
super.onBackPressed()
Toast.makeText(this,"See You Next Time!",Toast.LENGTH_SHORT).show()
}
}
}
Thanks in advance :)
Solution
- Create Kotlin file, e.g. named
Utils
; Move function to that file, and add
Context
parameter:fun checkConnectivity(ctx: Context): Boolean { val cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork =cm.activeNetworkInfo return activeNetwork != null && activeNetwork.isConnectedOrConnecting }
If you intend to use it only in
Activity
you can create extension function withoutContext
parameter:fun Activity.checkConnectivity(): Boolean { val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork =cm.activeNetworkInfo return activeNetwork != null && activeNetwork.isConnectedOrConnecting }
Call that function from wherever you want. If you call it from
Activity
just use code:checkConnectivity(this@YourActivity)
If you created extension function, just call it in
Activity
without passing any parameters:checkConnectivity()
Answered By - Sergey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.