欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android判断是Wifi还是4G网络代码

程序员文章站 2024-03-04 09:54:53
本文实例为大家分享了android判断是wifi还是4g网络的具体代码,供大家参考,具体内容如下 package com.chengxinet.bobo.util...

本文实例为大家分享了android判断是wifi还是4g网络的具体代码,供大家参考,具体内容如下

package com.chengxinet.bobo.utils;

import android.content.context;
import android.net.connectivitymanager;
import android.net.networkinfo;
import android.telephony.telephonymanager;

/**
 * created by administrator on 2016/1/7.
 */
public class networkutils {
  public static boolean isnetworkavailable(context c) {
    context context = c.getapplicationcontext();
    // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
    connectivitymanager connectivitymanager = (connectivitymanager) context.getsystemservice(context.connectivity_service);

    if (connectivitymanager == null) {
      return false;
    } else {
      // 获取networkinfo对象
      networkinfo[] networkinfo = connectivitymanager.getallnetworkinfo();

      if (networkinfo != null && networkinfo.length > 0) {
        for (networkinfo anetworkinfo : networkinfo) {
//          system.out.println(i + "===状态===" + networkinfo[i].getstate());
//          system.out.println(i + "===类型===" + networkinfo[i].gettypename());
          // 判断当前网络状态是否为连接状态
          if (anetworkinfo.getstate() == networkinfo.state.connected) {
            return true;
          }
        }
      }
    }
    return false;
  }

  /**
   * 判断wifi是否打开
   * @param context
   * @return
   */
  public static boolean iswifienabled(context context) {
    connectivitymanager mgrconn = (connectivitymanager) context
        .getsystemservice(context.connectivity_service);
    telephonymanager mgrtel = (telephonymanager) context
        .getsystemservice(context.telephony_service);
    return ((mgrconn.getactivenetworkinfo() != null && mgrconn
        .getactivenetworkinfo().getstate() == networkinfo.state.connected) || mgrtel
        .getnetworktype() == telephonymanager.network_type_umts);
  }

  /**
   * 判断是否是3g网络
   * @param context
   * @return
   */
  public static boolean is3rd(context context) {
    connectivitymanager cm = (connectivitymanager) context
        .getsystemservice(context.connectivity_service);
    networkinfo networkinfo = cm.getactivenetworkinfo();
    if (networkinfo != null
        && networkinfo.gettype() == connectivitymanager.type_mobile) {
      return true;
    }
    return false;
  }

  /**
   * 判断是wifi还是3g网络
   * @param context
   * @return
   */
  public static boolean iswifi(context context) {
    connectivitymanager cm = (connectivitymanager) context
        .getsystemservice(context.connectivity_service);
    networkinfo networkinfo = cm.getactivenetworkinfo();
    if (networkinfo != null
        && networkinfo.gettype() == connectivitymanager.type_wifi) {
      return true;
    }
    return false;
  }
}

以上就是本文的全部内容,希望对大家学习android软件编程有所帮助。