当互联网连接丢失时,防止在webview中打开URL

时间:2017-12-18 15:42:03

标签: java android webview

我是Android编程的新手,我为我的网站创建了Webview应用程序,到目前为止没有问题,直到互联网连接丢失,我可以阻止在Webview点击某些链接时打开URL页面show"网页不可用"?

我的预期结果是:

Webview

中点击链接时显示Toast"没有互联网连接" 仍然在同一页面

我尝试在 onReceivedError

中使用
if (wv.canGoBack()) {wv.goBack();}

但仍然显示"网页不可用"并返回上一页

PS: 此代码显示Toast"没有互联网连接",但仍然显示"网页不可用"

mycode的

MainActivity.java

import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    WebView wv;
    String URL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(!isNetworkAvailable()){
            Toast.makeText(getApplicationContext(),"No Internet Connection",Toast.LENGTH_SHORT).show();
        }else{
            URL = "Https://resiongkir.dzakiyyah.com";
            wv = (WebView)findViewById(R.id.web);
            wv.setWebViewClient(new WebViewClient(){
                @Override
                public void onPageFinished(WebView view, String url){
                    findViewById(R.id.imageView1).setVisibility(View.GONE);
                    findViewById(R.id.web).setVisibility(View.VISIBLE);
                }

                @Override
                public void onReceivedError(WebView view, int errorCode,String description, final String failingUrl) {
                    Toast.makeText(getApplicationContext(), "No Internet Connection Or " + description , Toast.LENGTH_LONG).show();
                    super.onReceivedError(view, errorCode, description, failingUrl);
                }
            });
            wv.getSettings().setJavaScriptEnabled(true);
            wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            wv.getSettings().setBuiltInZoomControls(true);
            wv.loadUrl(URL);
        }
    }

    private boolean isNetworkAvailable(){
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
    }

    @Override
    public void onBackPressed(){
        if(wv.canGoBack()){
            wv.goBack();
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Anda yakin akan menutup ResiOngkir?")
                    .setCancelable(false)
                    .setPositiveButton("Ya", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            MainActivity.this.finish();
                        }
                    })
                    .setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.dzakiyyah.abu.resiongkir.MainActivity">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="228dp"
        android:layout_height="216dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:contentDescription="@string/app_logo"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.975"
        app:srcCompat="@drawable/muava" />


    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/web"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:3)

你应该提供一个替代的HTML来加载。如果很简单,只需要String!像这样:

@Override
public void onReceivedError(WebView view, int errorCode,String description, final String failingUrl) {
        Toast.makeText(getApplicationContext(), "No Internet Connection Or " + description , Toast.LENGTH_LONG).show();

        String error_summary = "<html><body> Dear User, An error happened <b>No internet</b> connection!.</body></html>";
        view.loadData(error_summary, "text/html", null);
        super.onReceivedError(view, errorCode, description, failingUrl);
}

但是如果你想让webPage拥有相同的Url(不加载任何新的东西),那么最好是根据你的评论使它INVISIBLE这是你想要的而不是加载任何东西只是让webview看不见导致空白页面!

而不是在onReceivedError中加载任何内容:

view.setVisibility(View.INVISIBLE);

当互联网连接记得再次使其VISIBLE时:

wv.setVisibility(View.VISIBLE);