How to show message if no internet available in my android webview

前端 未结 6 1803
野的像风
野的像风 2020-12-30 17:07

Hi I am working with android webview application.I uses my the url succesfully in my app and it works only if internet connection available .But I want to show some messages

相关标签:
6条回答
  • 2020-12-30 17:16

    Create a new class and check in any other activity like

    MainActivity.java

    if (AppStatus.getInstance(this).isOnline(this)) {
    
                Toast.makeText(getBaseContext(),
                        "Internet connection available", 4000).show();
                       // do your stuff
            }
    
            else
            {
                Toast.makeText(getBaseContext(),
                        "No Internet connection available", 4000).show();
            }
    

    AppStatus .java

    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.util.Log;
    
    
    public class AppStatus {
    
        private static AppStatus instance = new AppStatus();
        static Context context;
        ConnectivityManager connectivityManager;
        NetworkInfo wifiInfo, mobileInfo;
        boolean connected = false;
    
        public static AppStatus getInstance(Context ctx) {
            context = ctx;
            return instance;
        }
    
        public boolean isOnline(Context con) {
            try {
                connectivityManager = (ConnectivityManager) con
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
    
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            return connected;
    
    
            } catch (Exception e) {
                System.out.println("CheckConnectivity Exception: " + e.getMessage());
                Log.v("connectivity", e.toString());
            }
            return connected;
        }
    }
    
    0 讨论(0)
  • 2020-12-30 17:19

    Call this method before opening the webView if this method returns true that means the internet connection is avialable and you can process to the webview otherwise show some Toast or you can show Dialog if this method returns false.

    Edit

    Use this code like in your Main Activity as like this

    if(isNetworkStatusAvialable (getApplicationContext())) {
        Toast.makeText(getApplicationContext(), "internet avialable", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_SHORT).show();
    
    }
    

    Method

    public static boolean isNetworkStatusAvialable (Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) 
        {
            NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
            if(netInfos != null)
            if(netInfos.isConnected()) 
                return true;
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-12-30 17:19

    If you are use internet connection check internet can be unavalable even if mobile or wi-fi network connected but your internet connection checker returns true https://stackoverflow.com/a/39883250/2212515 use something like that

    0 讨论(0)
  • 2020-12-30 17:20

    I did it this way:

    Create two java files as below:

    NetworkConnectivity.java

    package com.connectivity;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import android.app.Activity;
    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Handler;
    
    public class NetworkConnectivity {
    
        private static NetworkConnectivity sharedNetworkConnectivity = null;
    
        private Activity activity = null;
    
        private final Handler handler = new Handler();
        private Runnable runnable = null;
    
        private boolean stopRequested = false;
        private boolean monitorStarted = false;
    
        private static final int NETWORK_CONNECTION_YES = 1;
        private static final int NETWORK_CONNECTION_NO = -1;
        private static final int NETWORK_CONNECTION_UKNOWN = 0;
    
        private int connected = NETWORK_CONNECTION_UKNOWN;
    
        public static final int MONITOR_RATE_WHEN_CONNECTED_MS = 5000;
        public static final int MONITOR_RATE_WHEN_DISCONNECTED_MS = 1000;
    
        private final List<NetworkMonitorListener> networkMonitorListeners = new ArrayList<NetworkMonitorListener>();
    
        private NetworkConnectivity() {
        }
    
        public synchronized static NetworkConnectivity sharedNetworkConnectivity() {
            if (sharedNetworkConnectivity == null) {
                sharedNetworkConnectivity = new NetworkConnectivity();
            }
    
            return sharedNetworkConnectivity;
        }
    
        public void configure(Activity activity) {
            this.activity = activity;
        }
    
        public synchronized boolean startNetworkMonitor() {
            if (this.activity == null) {
                return false;
            }
    
            if (monitorStarted) {
                return true;
            }
    
            stopRequested = false;
            monitorStarted = true;
    
            (new Thread(new Runnable() {
                @Override
                public void run() {
                    doCheckConnection();
                }
            })).start();
    
            return true;
        }
    
        public synchronized void stopNetworkMonitor() {
            stopRequested = true;
            monitorStarted = false;
        }
    
        public void addNetworkMonitorListener(NetworkMonitorListener l) {
            this.networkMonitorListeners.add(l);
            this.notifyNetworkMonitorListener(l);
        }
    
        public boolean removeNetworkMonitorListener(NetworkMonitorListener l) {
            return this.networkMonitorListeners.remove(l);
        }
    
        private void doCheckConnection() {
    
            if (stopRequested) {
                runnable = null;
                return;
            }
    
            final boolean connectedBool = this.isConnected();
            final int _connected = (connectedBool ? NETWORK_CONNECTION_YES
                    : NETWORK_CONNECTION_NO);
    
            if (this.connected != _connected) {
    
                this.connected = _connected;
    
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        notifyNetworkMonitorListeners();
                    }
                });
            }
    
            runnable = new Runnable() {
                @Override
                public void run() {
                    doCheckConnection();
                }
            };
    
            handler.postDelayed(runnable,
                    (connectedBool ? MONITOR_RATE_WHEN_CONNECTED_MS
                            : MONITOR_RATE_WHEN_DISCONNECTED_MS));
        }
    
        public boolean isConnected() {
            try {
                ConnectivityManager cm = (ConnectivityManager) activity
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
    
                if (netInfo != null && netInfo.isConnected()) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        }
    
        private void notifyNetworkMonitorListener(NetworkMonitorListener l) {
            try {
                if (this.connected == NETWORK_CONNECTION_YES) {
                    l.connectionEstablished();
                } else if (this.connected == NETWORK_CONNECTION_NO) {
                    l.connectionLost();
                } else {
                    l.connectionCheckInProgress();
                }
            } catch (Exception e) {
            }
        }
    
        private void notifyNetworkMonitorListeners() {
            for (NetworkMonitorListener l : this.networkMonitorListeners) {
                this.notifyNetworkMonitorListener(l);
            }
        }
    
    }
    

    NetworkMonitorListener.java

    package com.connectivity;
    
    public interface NetworkMonitorListener {
    
        public void connectionEstablished();
        public void connectionLost();
        public void connectionCheckInProgress();
    }
    

    And finally, the usage:

    NetworkConnectivity.sharedNetworkConnectivity().configure(this);
            NetworkConnectivity.sharedNetworkConnectivity().startNetworkMonitor();
            NetworkConnectivity.sharedNetworkConnectivity()
                    .addNetworkMonitorListener(new NetworkMonitorListener() {
                        @Override
                        public void connectionCheckInProgress() {
                            // Okay to make UI updates (check-in-progress is rare)
                        }
    
                        @Override
                        public void connectionEstablished() {
                            // Okay to make UI updates -- do something now that
                            // connection is avaialble
    
                            Toast.makeText(getBaseContext(), "Connection established", Toast.LENGTH_SHORT).show();
                        }
    
                        @Override
                        public void connectionLost() {
                            // Okay to make UI updates -- bummer, no connection
    
                            Toast.makeText(getBaseContext(), "Connection lost.", Toast.LENGTH_LONG).show();
                        }
                    });
    

    With the above usage, you will be able to check for internet connection in runtime. As soon as the internet connection is lost, Toast will appear (as per the above code).

    0 讨论(0)
  • 2020-12-30 17:32

    as Brain said on this post
    To determine when the device has a network connection, request the permission <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> and then you can check with the following code. First define these variables as class variables.

    private Context c;
    private boolean isConnected = true;
    

    In your onCreate() method initialize c = this;

    Then check for connectivity.

    ConnectivityManager connectivityManager = (ConnectivityManager)
        c.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
        if (ni.getState() != NetworkInfo.State.CONNECTED) {
            // record the fact that there is not connection
            isConnected = false;
        }
    }
    

    Then to intercept the WebView requets, you could do something like the following. If you use this, you will probably want to customize the error messages to include some of the information that is available in the onReceivedError method.

    final String offlineMessageHtml = "DEFINE THIS";
    final String timeoutMessageHtml = "DEFINE THIS";
    
    WebView browser = (WebView) findViewById(R.id.webview);
    browser.setNetworkAvailable(isConnected);
    browser.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (isConnected) {
                // return false to let the WebView handle the URL
                return false;
            } else {
                // show the proper "not connected" message
                view.loadData(offlineMessageHtml, "text/html", "utf-8");
                // return true if the host application wants to leave the current 
                // WebView and handle the url itself
                return true;
            }
        }
        @Override
        public void onReceivedError (WebView view, int errorCode, 
            String description, String failingUrl) {
            if (errorCode == ERROR_TIMEOUT) {
                view.stopLoading();  // may not be needed
                view.loadData(timeoutMessageHtml, "text/html", "utf-8");
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-30 17:43

    Use Below code:

    boolean internetCheck;
    /*
         * 
         * Method to check Internet connection is available
         */
    
        public static boolean isInternetAvailable(Context context) {
            boolean haveConnectedWifi = false;
            boolean haveConnectedMobile = false;
            boolean connectionavailable = false;
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            NetworkInfo informationabtnet = cm.getActiveNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                try {
    
                    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                        if (ni.isConnected())
                            haveConnectedWifi = true;
                    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                        if (ni.isConnected())
                            haveConnectedMobile = true;
                    if (informationabtnet.isAvailable()
                            && informationabtnet.isConnected())
                        connectionavailable = true;
    
                } catch (Exception e) {
                    // TODO: handle exception
                    System.out.println("Inside utils catch clause , exception is"
                            + e.toString());
                    e.printStackTrace();
                    /*
                     * haveConnectedWifi = false; haveConnectedMobile = false;
                     * connectionavailable = false;
                     */
                }
            }
            return haveConnectedWifi || haveConnectedMobile;
        }
    

    It return true if network is available otherwise false In the mantifest add below permissions

    <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    0 讨论(0)
提交回复
热议问题