[英]“restart” app if no internet connection
I am building a webview where if there is no internet connection, it will load a local error html file. 我正在建立一个webview,如果没有互联网连接,它将加载本地错误html文件。 I made it work in my MainActivity which is where the webview is created.
我在创建网络视图的MainActivity中使其工作。 But I am having a problem accessing my webview from ourViewClient that handles all the stuff happening inside the webview.
但是我在从ourViewClient访问Webview时遇到问题,该问题处理了webview内部发生的所有事情。 So i cannot use the
browser.loadUrl("file:///android_asset/error.html");
所以我不能使用
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.
我尝试使用Intent,但是当我没有互联网连接时,按网页上的按钮绝对不会发生任何事情。 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?
是否有可能用一个命令替换意图,该命令会重新启动应用程序并从头开始,以便它再次检查MainActivity中的Internet连接? I am a beginner at this so please explain simple
我是初学者,所以请简单说明
This is the intent that does not work in ourViewClient 这是在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. 您将必须运行一个计时器,该计时器将在一段时间后检查Internet连接是否可用。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.