检查ANDROID互联网连接 [英] Check internet connection in ANDROID

查看:155
本文介绍了检查ANDROID互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我可以检测与连接

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

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

这篇关于检查ANDROID互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆