我在此kotlin代码中需要帮助...我具有checkConnctivvity()函数,并且运行正常...
fun checkConnectivity(){
val cm=getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork =cm.activeNetworkInfo
val isConnected=activeNetwork != null && activeNetwork.isConnectedOrConnecting}
1 /我尝试了其他方法从其他活动中调用它的方法,但是我无法...如何解决该问题
2 /我想在webChromeClient中添加checkConnectivity()函数,因此每次progressBarChanged都会验证连接..但没有起作用
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()
}
}
}
预先感谢:)
答案 0 :(得分:1)
Utils
; 将功能移至该文件,并添加Context
参数:
fun checkConnectivity(ctx: Context): Boolean {
val cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork =cm.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnectedOrConnecting
}
如果仅打算在Activity
中使用它,则可以创建不带Context
参数的扩展功能:
fun Activity.checkConnectivity(): Boolean {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork =cm.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnectedOrConnecting
}
从任意位置调用该函数。如果您从Activity
调用它,只需使用代码:
checkConnectivity(this@YourActivity)
如果您创建了扩展功能,只需在Activity
中调用它而无需传递任何参数:
checkConnectivity()