0

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)
   }
Zeni
  • 677
  • 1
  • 7
  • 20

2 Answers2

0

You are supposed to put below code in your onCreate() method. By this you will be able to register your call back for listening to Internet connectivity changes

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
    }
})

}

Hope this helps you.

Abdul Waheed
  • 3,994
  • 4
  • 30
  • 49
  • If I put this code in onCreate() method and I put setContentView(myWebView) myWebView.loadUrl("https://xxxxxxx.com/xxx/xxx.html") inside fun when network is available, the app crashes. If I don't set content or load url, it works. – Zeni Dec 02 '19 at 15:33
  • Do something like this webView.setWebViewClient(WebViewClient()) webView.loadUrl(url) – Manoj Mohanty Dec 02 '19 at 17:00
0

Add A broadcast receiver for network changes class NetworkChangeReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        //Check if connected
        context.sendBroadcast(new Intent("INTERNET_CONNECTED"));
    }
}

Register the receiver in manifest as follows

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<receiver
        android:name="NetworkChangeReceiver"
        android:label="NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
</receiver>

Now in your activity create a broadcast receiver to receive the result for internet change

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    registerReceiver(broadcastReceiver, new IntentFilter("INTERNET_CONNECTED"));
}

val broadcastReceiver = object : BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        //do your webview code here
    }
}

override fun onDestroy() {
    super.onDestroy()
    unregisterReceiver(broadcastReceiver);
}