检查ANDROID中的互联网连接

M.V*_*.V. 5 connection android

你好我有基于互联网检索数据的应用程序...

如果没有可用的连接,我该如何处理我的应用程序?

我可以检测到连接

ConnectivityManager cm = (ConnectivityManager) 
getSystemService(this.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
Run Code Online (Sandbox Code Playgroud)

它工作正常......但是当我知道没有连接时,我怎么能阻止Force Erros呢?我希望显示一条消息 - 例如:"抱歉!没有可用的互联网连接!" 而不是我的粉碎申请...

pec*_*eps 36

 /**
   * Checks if the device has Internet connection.
   * 
   * @return <code>true</code> if the phone is connected to the Internet.
   */
  public static boolean hasConnection() {
    ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
        Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
      return true;
    }

    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
      return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
      return true;
    }

    return false;
  }
Run Code Online (Sandbox Code Playgroud)