簡體   English   中英

斷開互聯網連接后,防止在Web視圖中打開URL

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

我是android編程的新手,我為自己的網站創建了Webview應用程序,到目前為止直到互聯網連接斷開為止都沒有問題,當我單擊Webview某些鏈接而不顯示“網頁不可用”時,是否可以阻止打開URL頁面?

我的預期結果是:

當我單擊Webview鏈接時, 顯示Toast“沒有Internet連接”並且仍在同一頁面

我嘗試在onReceivedError中使用:

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

但仍然顯示“網頁不可用”並返回上一頁

PS: 此代碼顯示Toast“無Internet連接”,但仍顯示“網頁不可用”

我的密碼

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>

您應該提供備用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);
}

但是如果你想的網頁有相同的URL(不加載任何新的東西),最好是讓它INVISIBLE ,這是您可以根據您的意見不必加載任何的希望只是做一個web視圖不可見,導致一個空白頁什么!

不用在onReceivedError中加載任何東西,而是這樣做:

view.setVisibility(View.INVISIBLE);

當Internet連接記住再次使其VISIBLE時:

wv.setVisibility(View.VISIBLE);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM