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

所属分类: 软件编程 / Android 阅读数: 54
收藏 0 赞 0 分享

前言

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

总结

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

更多精彩内容其他人还在看

使用ViewPager实现android软件使用向导功能实现步骤

现在的大部分android软件,都是使用说明,就是第一次使用该软件时,会出现向导,可以左右滑动,然后就进入应用的主界面了,下面我们就实现这个功能
收藏 0 赞 0 分享

android在异步任务中关闭Cursor的代码方法

android在异步任务中如何关闭Cursor?在我们开发应用的时候,很多时候会遇到这种问题,下面我们就看看代码如何实现
收藏 0 赞 0 分享

Android自定义桌面功能代码实现

android自定义桌面其实很简单,看一个例子就明白了
收藏 0 赞 0 分享

android将图片转换存到数据库再从数据库读取转换成图片实现代码

有时候我们想把图片存入到数据库中,尽管这不是一种明智的选择,但有时候还是不得以会用到,下面说说将图片转换成byte[]数组存入到数据库中去,并从数据库中取出来转换成图像显示出来
收藏 0 赞 0 分享

TextView显示系统时间(时钟功能带秒针变化

用System.currentTimeMillis()可以获取系统当前的时间,我们可以开启一个线程,然后通过handler发消息,来实时的更新TextView上显示的系统时间,可以做一个时钟的功能
收藏 0 赞 0 分享

Android用ListView显示SDCard文件列表的小例子

本文简单实现了用ListView显示SDCard文件列表,目录的回退等功能暂不讨论,获取文件列表,files即为所选择目录下的所有文件列表
收藏 0 赞 0 分享

Android拦截外拨电话程序示例

这篇文章主要介绍了Android拦截外拨电话的示例,大家参考使用吧
收藏 0 赞 0 分享

通过Html网页调用本地安卓(android)app程序代码

如何使用html网页和本地app进行传递数据呢?经过研究,发现还是有方法的,总结了一下,大致有一下几种方式
收藏 0 赞 0 分享

android Textview文字监控(Textview使用方法)

以手机号充值为例,当用户输入最后一位数时候,进行汇率的变换,本文就实现类似这样的功能
收藏 0 赞 0 分享

Android ListView长按弹出菜单二种实现方式示例

这篇文章主要介绍了Android ListView长按弹出菜单的方法,大家参考实现
收藏 0 赞 0 分享
查看更多