【问题标题】:How to show message if no internet available in my android webview如果我的 android webview 中没有可用的互联网,如何显示消息
【发布时间】:2016-10-06 04:44:58
【问题描述】:

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

【问题讨论】:

    标签: android webview alert


    【解决方案1】:

    在打开webView之前调用这个方法如果这个方法returns true这意味着互联网连接可用并且你可以处理到webview否则显示一些Toast或者你可以显示@ 987654324@如果这个方法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;
    }
    

    【讨论】:

    • 你有权限吗??? <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    • 好的我已经编辑了答案你现在检查了吗? logcat 的输出是什么??
    • 你也可以建议如何使它的 UI 更漂亮..nw 它的 jst 带有启动屏幕的 webview。
    • 你想要什么UI?你有什么要求??
    • 我只是想让 webview 更具吸引力..这意味着我希望在加载 web 内容时对页面的顶部和底部进行一些设计。
    【解决方案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 在清单中添加以下权限

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

    【讨论】:

      【解决方案3】:

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

      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 请求,您可以执行以下操作。如果您使用它,您可能需要自定义错误消息以包含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");
              }
          }
      });
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

          我是这样做的:

          创建两个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 就会出现(按照上面的代码)。

          【讨论】:

            【解决方案6】:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-01-07
              • 2019-12-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-11-25
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多