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

Android获得设备状态信息、Mac地址、IP地址的方法

程序员文章站 2022-08-20 16:20:51
前言 在app开发时,经常会遇到要获取手机状态信息的场景,像升级时获取版本号,像发生异常时要收集手机信息等等。有些软件还要根据mac地址来判定当前用户以前是否登录过。下面...

前言

在app开发时,经常会遇到要获取手机状态信息的场景,像升级时获取版本号,像发生异常时要收集手机信息等等。有些软件还要根据mac地址来判定当前用户以前是否登录过。下面将一一介绍获取这些手机状态信息的方法。

1 通过build获取手机硬件信息

  • 运用反射获取build信息,然后从build中得到对应字段的值。这种情况适用于获取所有的build信息。
  • 或者直接调用build类直接拿里面的字段名,如:android.os.build.model; // 手机型号 。这是为了获取单独某个手机信息的方法,直接调用build的字段即可拿到对应信息,简单快捷。
  • 别忘了加权限
<uses-permission android:name="android.permission.read_phone_state"/>

下面是build类的字段所对应的信息

string board    the name of the underlying board, like "goldfish".基板名
string bootloader the system bootloader version number.
string brand    the brand (e.g., carrier) the software is customized for, if any.品牌名
string cpu_abi   the name of the instruction set (cpu type + abi convention) of native code.
string cpu_abi2  the name of the second instruction set (cpu type + abi convention) of native code.
string device   the name of the industrial design.品牌型号名,如小米4对应cancro
string display   a build id string meant for displaying to the user
string fingerprint a string that uniquely identifies this build.包含制造商,设备名,系统版本等诸多信息
string hardware  the name of the hardware (from the kernel command line or /proc).
string host   
string id     either a changelist number, or a label like "m4-rc20".
string manufacturer  the manufacturer of the product/hardware.
string model    the end-user-visible name for the end product.
string product   the name of the overall product.
string radio    the radio firmware version number.
string serial   a hardware serial number, if available.
string tags    comma-separated tags describing the build, like "unsigned,debug".
long  time    当前时间,毫秒值
string type    the type of build, like "user" or "eng".
string unknown   value used for when a build property is unknown.
string user
//运用反射得到build类里的字段
 field[] fields = build.class.getdeclaredfields();
    //遍历字段名数组
    for (field field : fields) {
      try {
        //将字段都设为public可获取
        field.setaccessible(true);
        //filed.get(null)得到的即是设备信息
        haspmap.put(field.getname(), field.get(null).tostring());
        log.d("crashhandler", field.getname() + " : " + field.get(null));
      } catch (exception e) {
      }
    }

下面是小米4对应的设备信息

d/crashhandler: board : msm8974
d/crashhandler: bootloader : unknown
d/crashhandler: brand : xiaomi
d/crashhandler: cpu_abi : armeabi-v7a
d/crashhandler: cpu_abi2 : armeabi
d/crashhandler: device : cancro
d/crashhandler: display : mmb29m
d/crashhandler: fingerprint : xiaomi/cancro_wc_lte/cancro:6.0.1/mmb29m/v8.1.3.0.mxdcndi:user/release-keys
d/crashhandler: hardware : qcom
d/crashhandler: host : c3-miui-ota-bd43
d/crashhandler: id : mmb29m
d/crashhandler: is_debuggable : false
d/crashhandler: manufacturer : xiaomi
d/crashhandler: model : mi 4lte
d/crashhandler: product : cancro_wc_lte
d/crashhandler: radio : unknown
//设备的序列号码-serial
d/crashhandler: serial : abcdefgh
d/crashhandler: supported_32_bit_abis : [ljava.lang.string;@76b6d2b
d/crashhandler: supported_64_bit_abis : [ljava.lang.string;@e42c588
d/crashhandler: supported_abis : [ljava.lang.string;@9cdbb21
d/crashhandler: tag : build
d/crashhandler: tags : release-keys
d/crashhandler: time : 1478606340000
d/crashhandler: type : user
d/crashhandler: unknown : unknown
d/crashhandler: user : builder

2.通过getsystemservice()来获取ip地址

context.getsystemservice()这个方法是非常实用的方法,只须在参数里输入一个string 字符串常量就可得到对应的服务管理方法,可以用来获取绝大部分的系统信息,各个常量对应的含义如下。

window_service (“window”)
the top-level window manager in which you can place custom windows. the returned object is a windowmanager.

layout_inflater_service (“layout_inflater”)
a layoutinflater for inflating layout resources in this context.

activity_service (“activity”)
a activitymanager for interacting with the global activity state of the system.

power_service (“power”)
a powermanager for controlling power management.

alarm_service (“alarm”)
a alarmmanager for receiving intents at the time of your choosing.
notification_service (“notification”)
a notificationmanager for informing the user of background events.

keyguard_service (“keyguard”)
a keyguardmanager for controlling keyguard.

location_service (“location”)
a locationmanager for controlling location (e.g., gps) updates.

search_service (“search”)
a searchmanager for handling search.

vibrator_service (“vibrator”)
a vibrator for interacting with the vibrator hardware.

connectivity_service (“connection”)
a connectivitymanager for handling management of network connections.

wifi_service (“wifi”)
a wifimanager for management of wi-fi connectivity.

wifi_p2p_service (“wifip2p”)
a wifip2pmanager for management of wi-fi direct connectivity.

input_method_service (“input_method”)
an inputmethodmanager for management of input methods.

ui_mode_service (“uimode”)
an uimodemanager for controlling ui modes.

download_service (“download”)
a downloadmanager for requesting http downloads

battery_service (“batterymanager”)
a batterymanager for managing battery state

job_scheduler_service (“taskmanager”)
a jobscheduler for managing scheduled tasks

network_stats_service (“netstats”)
a networkstatsmanager for querying network usage statistics.
note: system services obtained via this api may be closely associated with the context in which they are obtained from. in general, do not share the service objects between various different contexts (activities, applications, services, providers, etc.)

parameters
name
the name of the desired service.

returns
the service or null if the name does not exist.

要获取ip地址需要用到context.connectivity_service,这个常量所对应的网络连接的管理方法。

代码如下需要权限:

<uses-permission android:name="android.permission.access_network_state" />
/**获得ip地址,分为两种情况,一是wifi下,二是移动网络下,得到的ip地址是不一样的*/
  public static string getipaddress() {
    context context=myapp.getcontext();
    networkinfo info = ((connectivitymanager) context
        .getsystemservice(context.connectivity_service)).getactivenetworkinfo();
    if (info != null && info.isconnected()) {
      if (info.gettype() == connectivitymanager.type_mobile) {//当前使用2g/3g/4g网络
        try {
          //enumeration<networkinterface> en=networkinterface.getnetworkinterfaces();
          for (enumeration<networkinterface> en = networkinterface.getnetworkinterfaces(); en.hasmoreelements(); ) {
            networkinterface intf = en.nextelement();
            for (enumeration<inetaddress> enumipaddr = intf.getinetaddresses(); enumipaddr.hasmoreelements(); ) {
              inetaddress inetaddress = enumipaddr.nextelement();
              if (!inetaddress.isloopbackaddress() && inetaddress instanceof inet4address) {
                return inetaddress.gethostaddress();
              }
            }
          }
        } catch (socketexception e) {
          e.printstacktrace();
        }
      } else if (info.gettype() == connectivitymanager.type_wifi) {//当前使用无线网络
        wifimanager wifimanager = (wifimanager) context.getsystemservice(context.wifi_service);
        wifiinfo wifiinfo = wifimanager.getconnectioninfo();
        //调用方法将int转换为地址字符串
        string ipaddress = intip2stringip(wifiinfo.getipaddress());//得到ipv4地址
        return ipaddress;
      }
    } else {
      //当前无网络连接,请在设置中打开网络
    }
    return null;
  }
  /**
   * 将得到的int类型的ip转换为string类型
   * @param ip
   * @return
   */
  public static string intip2stringip(int ip) {
    return (ip & 0xff) + "." +
        ((ip >> 8) & 0xff) + "." +
        ((ip >> 16) & 0xff) + "." +
        (ip >> 24 & 0xff);
  }

3.获得mac地址

我们知道mac地址是网卡的唯一标识,通过这个可以判断网络当前连接的手机设备有几台。代码如下:

 public static string getmacaddress(){
 /*获取mac地址有一点需要注意的就是android 6.0版本后,以下注释方法不再适用,不管任何手机都会返回"02:00:00:00:00:00"这个默认的mac地址,这是googel官方为了加强权限管理而禁用了getsystemservice(context.wifi_service)方法来获得mac地址。*/
 //    string macaddress= "";
//    wifimanager wifimanager = (wifimanager) myapp.getcontext().getsystemservice(context.wifi_service);
//    wifiinfo wifiinfo = wifimanager.getconnectioninfo();
//    macaddress = wifiinfo.getmacaddress();
//    return macaddress;
    string macaddress = null;
    stringbuffer buf = new stringbuffer();
    networkinterface networkinterface = null;
    try {
      networkinterface = networkinterface.getbyname("eth1");
      if (networkinterface == null) {
        networkinterface = networkinterface.getbyname("wlan0");
      }
      if (networkinterface == null) {
        return "02:00:00:00:00:02";
      }
      byte[] addr = networkinterface.gethardwareaddress();
      for (byte b : addr) {
        buf.append(string.format("%02x:", b));
      }
      if (buf.length() > 0) {
        buf.deletecharat(buf.length() - 1);
      }
      macaddress = buf.tostring();
    } catch (socketexception e) {
      e.printstacktrace();
      return "02:00:00:00:00:02";
    }
    return macaddress;
  }

4.获取手机号码、imei码

 /**获取手机的imei号码*/
  public static string getphoneimei() {
    telephonymanager mtm = (telephonymanager) myapp.getcontext().getsystemservice(context.telephony_service);
    string imei = mtm.getdeviceid();
    string imsi = mtm.getsubscriberid();
    string mtype = android.os.build.model; // 手机型号
    string numer = mtm.getline1number(); // 手机号码,有的可得,有的不可得
    return imei;
  }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接