I am building a webview where if there is no internet connection, it will load a local error html file. I made it work in my MainActivity which is where the webview is created. But I am having a problem accessing my webview from ourViewClient that handles all the stuff happening inside the webview. So i cannot use the browser.loadUrl("file:///android_asset/error.html");
inside that class. I tried using intent but absolutely nothing happens when i press a button on my web page when i have no internet connection. Is there a possibility of replacing the intent with a command which kinda restarts the app and start from the beginning so it checks for internet connection in the MainActivity again? I am a beginner at this so please explain simple
This is the intent that does not work in ourViewClient
if (CheckNetwork.isInternetAvailable(context)) {
return false;
} else {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("file:///android_asset/error.html"));
context.startActivity(intent);
}
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mClass = new ourViewClient(this);
browser = (WebView) findViewById(R.id.wvwMain);
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setLoadWithOverviewMode(true);
browser.getSettings().setUseWideViewPort(true);
browser.setWebViewClient(new ourViewClient(this));
if(CheckNetwork.isInternetAvailable(MainActivity.this)){
browser.loadUrl("http://MyWebPage");
} else {
browser.loadUrl("file:///android_asset/error.html");
}
}
You will have to run a timer which will check if Internet connection is available or not after a certain period.
Example:
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Check internet connection here
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//check once every 10 seconds, you might want to do this less frequently as checking network is a costly operation
10000);
And to restart your Activity do something like this.
if (Build.VERSION.SDK_INT >= 11) {
recreate(); //This method is only available on Android version 11 and above
} else {
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
overridePendingTransition(0, 0);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.