如果我的 android webview 中没有可用的互联网,如何显示消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20989485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:47:23  来源:igfitidea点击:

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

androidwebviewalert

提问by ptm

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 when there is no internet connection.how can i do this ???please help me since I am new to android development and thanks :)

嗨,我正在使用 android webview 应用程序。我在我的应用程序中成功地使用了我的 url,它只有在互联网连接可用时才有效。但我想在没有互联网连接时显示一些消息。我该怎么做????请帮助我,因为我是 android 开发的新手,谢谢:)

回答by

Call this method before opening the webViewif this method returns truethat means the internet connection is avialableand you can process to the webview otherwise show some Toastor you can show Dialogif this method returns false.

在打开webViewif this 方法之前调用此方法,这returns true意味着Internet 连接可用,您可以处理 webview 否则显示一些Toast或者您可以显示Dialog此方法returns false

Edit

编辑

Use this code like in your Main Activityas like this

在您使用此代码就像Main Activity是这样的

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

回答by FxRi4

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.

正如 Brain 在这篇文章中所说,
要确定设备何时有网络连接,请请求权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />,然后您可以使用以下代码进行检查。首先将这些变量定义为类变量。

private Context c;
private boolean isConnected = true;

In your onCreate()method initialize c = this;

在你的onCreate()方法中初始化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 WebViewrequets, 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 onReceivedErrormethod.

然后拦截WebView请求,您可以执行以下操作。如果您使用它,您可能希望自定义错误消息以包含该onReceivedError方法中可用的一些信息。

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

回答by jyomin

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

如果网络可用则返回 true 否则返回 false 在清单中添加以下权限

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

回答by Looking Forward

Create a new class and check in any other activity like

创建一个新类并检查任何其他活动,例如

MainActivity.java

主活动.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

应用状态.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;
    }
}

回答by Chintan Soni

I did it this way:

我是这样做的:

Create two java files as below:

创建两个java文件如下:

NetworkConnectivity.java

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

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, Toastwill appear (as per the above code).

通过上述用法,您将能够在运行时检查互联网连接。一旦互联网连接丢失,Toast就会出现(按照上面的代码)。

回答by user2212515

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/2212515use something like that

如果您使用互联网连接检查互联网可能无法使用,即使移动或 Wi-Fi 网络已连接但您的互联网连接检查器返回 true https://stackoverflow.com/a/39883250/2212515使用类似的东西