简体   繁体   中英

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"?

My Expected result is:

Show Toast "No Internet Connection" and Still in Same Page when I click link in Webview

i try to use in 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"

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>

You should provide an alternative html to load then. If it is simple just a String is required! 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!

Instead of loading anything in onReceivedError do this:

view.setVisibility(View.INVISIBLE);

When the Internet Connection remember to make it VISIBLE again:

wv.setVisibility(View.VISIBLE);

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.

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