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

时间:2014-01-08 07:30:51

标签: android webview alert

您好我正在使用Android webview应用程序。我在我的应用程序中成功使用我的网址,它只在互联网连接可用时才有效。但我想在没有互联网连接时显示一些消息。我可以这样做吗? ??请帮助我,因为我是Android开发的新手,谢谢:)

6 个答案:

答案 0 :(得分:12)

在打开webView之前调用此方法,如果此方法returns true表示互联网连接可用,您可以处理到webview,否则显示一些Toast或者,如果此方法为Dialog,则可以显示returns false

修改

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();

}

方法

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

答案 1 :(得分:2)

使用以下代码:

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

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

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

答案 2 :(得分:2)

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

private Context c;
private boolean isConnected = true;

onCreate()方法初始化c = this;

然后检查连接性。

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

然后拦截WebView requets,您可以执行以下操作。如果您使用此功能,则可能需要自定义错误消息以包含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");
        }
    }
});

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

我是这样做的:

创建两个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

package com.connectivity;

public interface NetworkMonitorListener {

    public void connectionEstablished();
    public void connectionLost();
    public void connectionCheckInProgress();
}

最后,用法:

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

通过上述用法,您可以在运行时检查互联网连接。一旦互联网连接丢失,将出现Toast(根据上述代码)。

答案 5 :(得分:0)

如果您使用互联网连接检查互联网即使连接了移动或Wi-Fi网络但您的互联网连接检查器返回true https://stackoverflow.com/a/39883250/2212515也可以使用