我对android开发很陌生,所以对于非常基本的问题提前抱歉。
在我的应用程序开始时,我想检查网络是否可用并已连接,如果是,则加载 webView 并加载 URL。这是一个简单的部分,我做到了。
现在,如果在应用程序启动时没有网络可用,我希望用户通过单击按钮(也已完成)连接到互联网,一旦连接,setContentView 到 webView 并加载 URL(大难题)。
我在这里找到了下面的代码,但我不知道如何使用它或将它放在哪里。
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
//take action when network connection is gained
}
override fun onLost(network: Network?) {
//take action when network connection is lost
}
})
}
我的代码如下:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (supportActionBar != null)
supportActionBar?.hide()
val myWebView = WebView(this)
myWebView.settings.setDomStorageEnabled(true)
myWebView.settings.setJavaScriptCanOpenWindowsAutomatically(true)
myWebView.settings.setDatabaseEnabled(true)
myWebView.settings.javaScriptEnabled = true
myWebView.webViewClient = WebViewClient()
myWebView.addJavascriptInterface(WebAppInterface(this), "Android")
val cm = getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
val dialogBuilder = AlertDialog.Builder(this)
if (activeNetwork!=null)
{
if (activeNetwork.isConnected) {
// Toast.makeText(getApplicationContext(), "internet avialable", Toast.LENGTH_LONG).show();
setContentView(myWebView)
myWebView.loadUrl("https://xxxxxxx.com/xxx/xxx.html");
}
}else {
setContentView(R.layout.activity_main)
Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_LONG).show();
val alert = dialogBuilder.create()
// set title for alert dialog box
alert.setTitle("internet Not avialable")
// show alert dialog
alert.show()
}
}
fun EnableWiFi(){
val wifimanager=getApplicationContext().getSystemService(Context.WIFI_SERVICE) as WifiManager
wifimanager.setWifiEnabled(true)
}