检查ANDROID互联网连接互联网、ANDROID

2023-09-12 08:44:23 作者:如初〃

你好,我已经根据检索到的互联网数据应用...

如何处理的情况下我的应用程序没有连接可用?

我可以检测与连接

  ConnectivityManager厘米=(ConnectivityManager)
getSystemService(this.CONNECTIVITY_SERVICE);
返回cm.getActiveNetworkInfo()isConnectedOrConnecting()。
 

它正常工作......但我怎么能prevent力误差修改时,我知道有没有什么联系?我想一个消息显示 - 有点像:很抱歉,没有互联网连接可用!而不是我的应用程序,以粉碎......

解决方案

  / **
   *如果设备有互联网连接检查。
   *
   * @返回< code取代;真< / code取代;如果手机连接到互联网。
   * /
  公共静态布尔hasConnection(){
    ConnectivityManager厘米=(ConnectivityManager)MbridgeApp.getContext()。getSystemService(
        Context.CONNECTIVITY_SERVICE);

    的NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    如果(wifiNetwork =空&安培;!&安培; wifiNetwork.isConnected()){
      返回true;
    }

    的NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    如果(mobileNetwork =空&安培;!&安培; mobileNetwork.isConnected()){
      返回true;
    }

    的NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    如果(activeNetwork =空&安培;!&安培; activeNetwork.isConnected()){
      返回true;
    }

    返回false;
  }
 

如何通过USB将Android连接到PC的Internet连接

Hello I have application based on data retrieved over internet...

How can I handle my app in case there is no connection available?

I can detect connection with

ConnectivityManager cm = (ConnectivityManager) 
getSystemService(this.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();

It works fine... But how can I prevent Force Erros when I know there is no connection? I would like a message to be shown - something like: "Sorry! There is no internet connection available!" and not my application to crush...

解决方案

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