How to show No Internet connection dialog in webview | Android Studio

落花浮王杯 提交于 2021-02-19 06:03:06

问题


I'm trying to add a message in a web view, the message should come out when you do not have an Internet connection.

I have tried many ways but I always make a mistake that I do not understand.

I create a folder called "assets" and add a file "error.html" following a YouTube tutorial but it gives me errors

I will write my codes here without what I saw on YouTube.

Thank you

MainActivity.java

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {

    private WebView wv;
    private SwipeRefreshLayout sr;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setItemIconTintList(null);

        sr = (SwipeRefreshLayout) findViewById(R.id.sr);
        sr.setOnRefreshListener(this);
        wv=(WebView)findViewById(R.id.wv);
        WebSettings webSettings=wv.getSettings();
        webSettings.setJavaScriptEnabled(true);
        wv.loadUrl("//MyURL//");
            wv.setWebViewClient(new WebViewClient());

        wv.setWebViewClient(new CustomWebViewClient());
    }


    private class CustomWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(url.contains("//MyURL//")) {
                view.loadUrl(url);
            } else {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
            }
            return true;
        }

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.Inicio) {
            wv.loadUrl("//social//");
        } else if (id == R.id.Insta) {
            wv.loadUrl("//social//");
        } else if (id == R.id.Facebook) {
            wv.loadUrl("//social//");
        } else if (id == R.id.Twitter) {
            wv.loadUrl("//social//");
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onRefresh() {
        wv.reload();
        sr.setRefreshing(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {
            //if Back key pressed and webview can navigate to previous page
            wv.goBack();
            // go back to previous page
            return true;
        }
        else
        {
            finish();
            // finish the activity
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override

    public boolean dispatchKeyEvent(KeyEvent event) {
        int action = event.getAction();
        int keyCode = event.getKeyCode();
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (action == KeyEvent.ACTION_UP) {
                    // TODO
                }
                return false;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (action == KeyEvent.ACTION_DOWN) {
                    //TODO
                }
                return false;
            default:
                return super.dispatchKeyEvent(event);
        }
    }

}

Content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/app_bar_main">


    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/sr"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <WebView
        android:id="@+id/wv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </WebView>

    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>

Thank You


回答1:


1) Create DetectConnection.java Class to check internet is available or not.

import android.content.Context;
import android.net.ConnectivityManager;


public class DetectConnection {             
  public static boolean checkInternetConnection(Context context) {   

    ConnectivityManager con_manager = (ConnectivityManager) 
      context.getSystemService(Context.CONNECTIVITY_SERVICE);

    return (con_manager.getActiveNetworkInfo() != null
        && con_manager.getActiveNetworkInfo().isAvailable()
        && con_manager.getActiveNetworkInfo().isConnected());
  }
}

2) Change your code of onCreate method, before loading check whether internet is available or not,

wv = (WebView) findViewById(R.id.wv);
CustomWebViewClient c = new CustomWebViewClient();
wv.setWebViewClient(c);
wv.clearCache(true);
wv.clearHistory();
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.getSettings().setBuiltInZoomControls(true);
if (!DetectConnection.checkInternetConnection(this)) {
 wv.loadUrl("file:///android_asset/error.html"); //Change path if it is not correct
} else {      
 wv.loadUrl("http://www.google.com");
}

3) Change code of CustomWebViewClient. It is a class where you can get a callback for each URL. In that callback, Once a page finish loading you can check it.

// Function to load all URLs in same webview
    private class CustomWebViewClient extends WebViewClient {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if(url.contains("//MyURL//")) {
                    view.loadUrl(url);
                } else {
                    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(i);
                }

            return true;
        }

        @Override
        public void onLoadResource(WebView  view, String  url){
            if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
                wv.loadUrl("file:///android_asset/error.html"); //Change path if it is not correct
            }
        }

    }

4) Add ACCESS_NETWORK_STATE Permission in AndroidMenifest.xml.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


来源:https://stackoverflow.com/questions/55437061/how-to-show-no-internet-connection-dialog-in-webview-android-studio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!