当前位置 : 主页 > 编程语言 > java >

测试android网络连接状态

来源:互联网 收集:自由互联 发布时间:2021-06-28
testConnect class Xxx { boolean wifiConnected; boolean mobileConnected;private void checkNetworkConnection() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeInfo = conn
testConnect
class  Xxx {

    boolean wifiConnected;
    boolean mobileConnected;

	private void checkNetworkConnection() {
      ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
      if (activeInfo != null && activeInfo.isConnected()) {
          wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
          mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
          if(wifiConnected) {
              Log.i(TAG, getString(R.string.wifi_connection));
          } else if (mobileConnected){
              Log.i(TAG, getString(R.string.mobile_connection));
          }
      } else {
          wifiConnected = false;
          mobileConnected = false;
          Log.i(TAG, getString(R.string.no_wifi_or_mobile));
      }
    }
}
网友评论