I am very new to android development so sorry in advance for very basic question.
At start of my app I want to check if network is available and connected, If yes then load webView and load URL. This was an easy part and I did it.
Now if at start of app not network is available I want user to connect to internet by click of button (also done) and once connected, setContentView to webView and load URL (big puzzle).
I found the below code here , but I don't know how to use it or where to put it.
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
}
})
}
My code is as below:
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)
}