目前还不清楚如何实现导航/互联网连接错误。
我在这里尝试过代码Android WebView onReceivedError()
但它不起作用。
import android.app.Activity;
import android.net.ConnectivityManager;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView view;
private ImageView splashScreen;
private ImageView logo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
splashScreen = (ImageView) this.findViewById(R.id.spscreen);
logo = (ImageView) this.findViewById(R.id.logo);
String url = "some URL";
view = (WebView)this.findViewById(R.id.webView1);
view.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
logo.setVisibility(View.INVISIBLE);
splashScreen.setVisibility(View.INVISIBLE);
view.setVisibility(View.VISIBLE);
}
});
WebSettings s = view.getSettings();
s.setJavaScriptEnabled(true);
s.setCacheMode(WebSettings.LOAD_DEFAULT);
s.setDomStorageEnabled(true);
view.loadUrl(url);
}
}
答案 0 :(得分:1)
嗯,这个
有2个选项让loadUrl()启动并稍后使用onReceivedError()
处理错误view.setWebViewClient(new WebViewClient() {
@override
public void onPageFinished(WebView view, String url) {
// do your stuff here
logo.setVisibility(View.INVISIBLE);
splashScreen.setVisibility(View.INVISIBLE);
view.setVisibility(View.VISIBLE);
}
@override
void onReceivedError (WebView view,
WebResourceRequest request,
WebResourceError error){
if(error.getErrorCode () == WebViewClient.ERROR_CONNECT || error.getErrorCode () == WebViewClient.ERROR_HOST_LOOKUP || WebViewClient.ERROR_TIMEOUT){
Toast.makeText(context, "you are not connected!", Toast.LENGTH_LONG);
//do other stuff, hide views ...
}
}
});
尝试处理所有连接错误full list of error codes can be found here
或者使用this answer中的isOnline()方法来包装loadUrl()调用 需要权限android.permission.ACCESS_NETWORK_STATE
if(!isOnline()){
Toast.makeText(context, "you are not connected!", Toast.LENGTH_LONG);
}else{
view.loadUrl(url);
}
如果您需要第一个选项,那可能会更好,因为在没有实际互联网连接的情况下连接到Wifi会给您错误的结果。