简体   繁体   English

断开互联网连接后,防止在Web视图中打开URL

[英]Prevent opening an URL in a webview when the internet connection is lost

I'm newbie in android programming, I created Webview app for my website, so far no problem until internet connection is lost, can I prevent to open URL page when I click some link from Webview without show "webpage not available"? 我是android编程的新手,我为自己的网站创建了Webview应用程序,到目前为止直到互联网连接断开为止都没有问题,当我单击Webview某些链接而不显示“网页不可用”时,是否可以阻止打开URL页面?

My Expected result is: 我的预期结果是:

Show Toast "No Internet Connection" and Still in Same Page when I click link in Webview 当我单击Webview链接时, 显示Toast“没有Internet连接”并且仍在同一页面

i try to use in onReceivedError : 我尝试在onReceivedError中使用:

if (wv.canGoBack()) {wv.goBack();}

but still, show "Webpage not available" and back to previous page 但仍然显示“网页不可用”并返回上一页

PS: This code show Toast "No Internet Connection", but still show "Webpage not available" PS: 此代码显示Toast“无Internet连接”,但仍显示“网页不可用”

MyCode 我的密码

MainActivity.java 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 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>

You should provide an alternative html to load then. 您应该提供备用HTML以便随后加载。 If it is simple just a String is required! 如果很简单,只需一个String Like this: 像这样:

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

But if you want the webPage to have the same Url (not loading anything new), The best is to make it INVISIBLE this is what you want according to your comments Instead of loading anything just make a webview invisible leading to a blank page! 但是如果你想的网页有相同的URL(不加载任何新的东西),最好是让它INVISIBLE ,这是您可以根据您的意见不必加载任何的希望只是做一个web视图不可见,导致一个空白页什么!

Instead of loading anything in onReceivedError do this: 不用在onReceivedError中加载任何东西,而是这样做:

view.setVisibility(View.INVISIBLE);

When the Internet Connection remember to make it VISIBLE again: 当Internet连接记住再次使其VISIBLE时:

wv.setVisibility(View.VISIBLE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM