当前位置:   article > 正文

获取 手机基本配置信息 硬件 系统信息 辅助类_如何获取手机硬件配置

如何获取手机硬件配置
  1. package com.weedong.mobile.base;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileFilter;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.lang.reflect.InvocationTargetException;
  10. import java.lang.reflect.Method;
  11. import java.text.DecimalFormat;
  12. import java.util.regex.Pattern;
  13. import android.content.Context;
  14. import android.content.pm.PackageManager;
  15. import android.location.Location;
  16. import android.location.LocationManager;
  17. import android.net.ConnectivityManager;
  18. import android.net.NetworkInfo;
  19. import android.net.wifi.WifiInfo;
  20. import android.net.wifi.WifiManager;
  21. import android.os.Build;
  22. import android.os.Environment;
  23. import android.os.StatFs;
  24. import android.telephony.TelephonyManager;
  25. import android.text.TextUtils;
  26. import android.text.format.Formatter;
  27. import android.util.Log;
  28. /**
  29. * 获取 手机基本配置信息 硬件 系统信息
  30. *
  31. *
  32. */
  33. public class PhoneBaseInfoHelper {
  34. private static final String TAG = "PhoneBaseInfo";
  35. /**
  36. * sdCard大小
  37. * @return 单位:字节
  38. */
  39. public static long[] getSDCardMemory() {
  40. long[] sdCardInfo=new long[2];
  41. String state = Environment.getExternalStorageState();
  42. if (Environment.MEDIA_MOUNTED.equals(state)) {
  43. File sdcardDir = Environment.getExternalStorageDirectory();
  44. StatFs sf = new StatFs(sdcardDir.getPath());
  45. long bSize = sf.getBlockSize();
  46. long bCount = sf.getBlockCount();
  47. long availBlocks = sf.getAvailableBlocks();
  48. sdCardInfo[0] = bSize * bCount;//总大小
  49. sdCardInfo[1] = bSize * availBlocks;//可用大小
  50. }
  51. return sdCardInfo;
  52. }
  53. /**
  54. * 这个是手机内部存储的总空间大小 不是内存
  55. * @return bytes
  56. */
  57. public static long getTotalInternalMemorySize() {
  58. File path = Environment.getDataDirectory();
  59. StatFs stat = new StatFs(path.getPath());
  60. long blockSize = stat.getBlockSize();
  61. long totalBlocks = stat.getBlockCount();
  62. return totalBlocks * blockSize;
  63. }
  64. /**
  65. * 获取系统内存大小
  66. * @param context
  67. * @return MB
  68. */
  69. public static String getTotalMemory(Context context) {
  70. String str1 = "/proc/meminfo";// 系统内存信息文件
  71. String str2;
  72. String[] arrayOfString;
  73. long initial_memory = 0;
  74. try {
  75. FileReader localFileReader = new FileReader(str1);
  76. BufferedReader localBufferedReader = new BufferedReader(
  77. localFileReader, 8192);
  78. str2 = localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大小
  79. arrayOfString = str2.split("\\s+");
  80. // for (String num : arrayOfString) {
  81. // Log.i(str2, num + "\t");
  82. // }
  83. initial_memory = Integer.valueOf(arrayOfString[1]).intValue() <<10;// 获得系统总内存,单位是KB,乘以1024转换为Byte
  84. localBufferedReader.close();
  85. } catch (IOException e) {
  86. }
  87. return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB,内存大小规格化
  88. }
  89. /**
  90. * CPU信息
  91. * @return
  92. */
  93. public static String[] getCpuInfo() {
  94. String str1 = "/proc/cpuinfo";
  95. String str2="";
  96. String[] cpuInfo={"",""};
  97. String[] arrayOfString;
  98. try {
  99. FileReader fr = new FileReader(str1);
  100. BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
  101. str2 = localBufferedReader.readLine();
  102. Log.i("cpu1",str2);
  103. arrayOfString = str2.split("\\s+");
  104. for (int i = 2; i < arrayOfString.length; i++) {
  105. cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " "; //CPU的型号
  106. }
  107. str2 = localBufferedReader.readLine();
  108. Log.i("cpu2",str2);
  109. arrayOfString = str2.split("\\s+"); //CPU的频率 //非也!!
  110. cpuInfo[1] += arrayOfString[2];
  111. localBufferedReader.close();
  112. } catch (IOException e) {
  113. }
  114. return cpuInfo;
  115. }
  116. /**
  117. * 获取cpu 型号
  118. * @return ex: ARMv7 Processor rev 2 (v7l)
  119. */
  120. public static String getCpuModel(){
  121. String str = "";
  122. BufferedReader bufferedReader = null;
  123. try {
  124. FileReader fr = new FileReader("/proc/cpuinfo");
  125. if(fr != null){
  126. bufferedReader = new BufferedReader(fr, 1024);
  127. try {
  128. str = bufferedReader.readLine();
  129. bufferedReader.close();
  130. fr.close();
  131. } catch (IOException e) {
  132. Log.i(TAG, "Could not read from file /proc/cpuinfo", e);
  133. }
  134. }
  135. } catch (FileNotFoundException e) {
  136. Log.i(TAG, "Could not open file /proc/cpuinfo", e);
  137. }
  138. Log.i(TAG, "getCpu str: " + str);
  139. if(str != null){
  140. int i = str.indexOf(':') + 1;
  141. str = str.substring(i);
  142. }
  143. return str.trim();
  144. }
  145. /**
  146. * 系统的版本信息
  147. * @return
  148. */
  149. public static String[] getSysVersion(Context context){
  150. String[] version={"null","null","null","null","null"};
  151. String str1 = "/proc/version";
  152. String str2;
  153. String[] arrayOfString;
  154. try {
  155. FileReader localFileReader = new FileReader(str1);
  156. BufferedReader localBufferedReader = new BufferedReader(
  157. localFileReader, 8192);
  158. str2 = localBufferedReader.readLine();
  159. arrayOfString = str2.split("\\s+"); //防止 //s+
  160. version[0]=arrayOfString[2];//KernelVersion
  161. localBufferedReader.close();
  162. } catch (IOException e) {
  163. }
  164. version[1] = Build.VERSION.RELEASE; // firmware version 设备的系统版本 如2.2
  165. version[2]=Build.MODEL; //model 设备型号
  166. version[3]=Build.DISPLAY; //system version 版本号 定制版本不一样
  167. version[4] = Build.VERSION.SDK_INT +""; // 设备SDK版本 8
  168. return version;
  169. }
  170. /**
  171. * 获取当前使用网络
  172. * @param context
  173. * @return 2g,3g,wifi,unknow,null
  174. */
  175. public static String getNetWorkType(Context context){
  176. ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  177. NetworkInfo networkinfo = manager.getActiveNetworkInfo();
  178. if (networkinfo == null || !networkinfo.isAvailable()) {// 当前网络不可用
  179. return null;
  180. } else { // 当前网络可用,可执行交互操作
  181. int type = networkinfo.getType();
  182. int subType = networkinfo.getSubtype();
  183. if(type == ConnectivityManager.TYPE_WIFI){ //wifi网络
  184. return "wifi";
  185. }else if(type == ConnectivityManager.TYPE_MOBILE){ //手机网络
  186. switch (subType) {
  187. case TelephonyManager.NETWORK_TYPE_EVDO_0: //3g
  188. case TelephonyManager.NETWORK_TYPE_EVDO_A: //电信3G
  189. case TelephonyManager.NETWORK_TYPE_HSDPA: //联通3g
  190. case TelephonyManager.NETWORK_TYPE_HSPA: //3g
  191. case TelephonyManager.NETWORK_TYPE_HSUPA: //3g
  192. case TelephonyManager.NETWORK_TYPE_UMTS: //联通3g
  193. // NOT AVAILABLE YET IN API LEVEL 7
  194. case TelephonyManager.NETWORK_TYPE_EHRPD:
  195. case TelephonyManager.NETWORK_TYPE_EVDO_B:
  196. case TelephonyManager.NETWORK_TYPE_HSPAP:
  197. case TelephonyManager.NETWORK_TYPE_LTE:
  198. return "3g";
  199. case TelephonyManager.NETWORK_TYPE_1xRTT: //2g
  200. case TelephonyManager.NETWORK_TYPE_CDMA: //电信2G
  201. case TelephonyManager.NETWORK_TYPE_EDGE: //移动2G
  202. case TelephonyManager.NETWORK_TYPE_GPRS: //联通2G
  203. case TelephonyManager.NETWORK_TYPE_IDEN: //2g
  204. return "2g";
  205. default:
  206. return "unknow";
  207. }
  208. }else{
  209. return "unknow";
  210. }
  211. }
  212. }
  213. /**
  214. * 获取cpu核数
  215. * @return
  216. */
  217. public static int getNumCores() {
  218. //Private Class to display only CPU devices in the directory listing
  219. class CpuFilter implements FileFilter {
  220. @Override
  221. public boolean accept(File pathname) {
  222. //Check if filename is "cpu", followed by a single digit number
  223. if(Pattern.matches("cpu[0-9]", pathname.getName())) {
  224. return true;
  225. }
  226. return false;
  227. }
  228. }
  229. try {
  230. //Get directory containing CPU info
  231. File dir = new File("/sys/devices/system/cpu/");
  232. //Filter to only list the devices we care about
  233. File[] files = dir.listFiles(new CpuFilter());
  234. //Return the number of cores (virtual CPU devices)
  235. return files.length;
  236. } catch(Exception e) {
  237. //Default to return 1 core
  238. return 1;
  239. }
  240. }
  241. /**
  242. * cpu 最大频率 KHz
  243. * @return
  244. */
  245. public static String getMaxCpuFreq() {
  246. String result = "";
  247. ProcessBuilder cmd;
  248. try {
  249. String[] args = { "/system/bin/cat",
  250. "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
  251. cmd = new ProcessBuilder(args);
  252. Process process = cmd.start();
  253. InputStream in = process.getInputStream();
  254. byte[] re = new byte[24];
  255. while (in.read(re) != -1) {
  256. result = result + new String(re);
  257. }
  258. in.close();
  259. if(!TextUtils.isEmpty(result)){
  260. double r = Double.parseDouble(result);
  261. DecimalFormat df = new DecimalFormat("##0.00");
  262. result = df.format(r/1000000) + "GHz";
  263. }else{
  264. result = "N/A";
  265. }
  266. } catch (IOException ex) {
  267. ex.printStackTrace();
  268. result = "N/A";
  269. }
  270. return result.trim();
  271. }
  272. /**
  273. * cpu 最小频率 KHz
  274. * @return
  275. */
  276. public static String getMinCpuFreq() {
  277. String result = "";
  278. ProcessBuilder cmd;
  279. try {
  280. String[] args = { "/system/bin/cat",
  281. "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" };
  282. cmd = new ProcessBuilder(args);
  283. Process process = cmd.start();
  284. InputStream in = process.getInputStream();
  285. byte[] re = new byte[24];
  286. while (in.read(re) != -1) {
  287. result = result + new String(re);
  288. }
  289. in.close();
  290. } catch (IOException ex) {
  291. ex.printStackTrace();
  292. result = "N/A";
  293. }
  294. return result.trim();
  295. }
  296. /**
  297. * 当前频率 KHz
  298. * @return
  299. */
  300. public static String getCurCpuFreq() {
  301. String result = "N/A";
  302. try {
  303. FileReader fr = new FileReader(
  304. "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
  305. BufferedReader br = new BufferedReader(fr);
  306. String text = br.readLine();
  307. result = text.trim();
  308. } catch (FileNotFoundException e) {
  309. e.printStackTrace();
  310. } catch (IOException e) {
  311. e.printStackTrace();
  312. }
  313. return result;
  314. }
  315. /**
  316. * 获取手机imei 并不严谨
  317. * @param context
  318. * @return
  319. * Returns the unique device ID, for example,
  320. * the IMEI for GSM and the MEID or ESN for CDMA phones.
  321. * Return null if device ID is not available.
  322. */
  323. public static String getIMEI(Context context){
  324. TelephonyManager telephonyManager=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
  325. String deviceId=telephonyManager.getDeviceId();
  326. if(TextUtils.isEmpty(deviceId))
  327. deviceId="0";
  328. return deviceId;
  329. }
  330. /**
  331. * 获取uuid android id + device id
  332. * @param context
  333. * @return
  334. */
  335. public static String getUDID(Context context){
  336. TelephonyManager telephonyManager=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
  337. String uuid = android.provider.Settings.System.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID)+"-"+telephonyManager.getDeviceId();
  338. return uuid;
  339. }
  340. /***
  341. * 获取 设备序列号 硬件标识 若有则唯一
  342. * 但并不是每个设备都会获取到
  343. * @return
  344. */
  345. public static final String getDeviceSerial()
  346. {
  347. String serial;
  348. if(android.os.Build.VERSION.SDK_INT >= 9)
  349. {
  350. serial = Build.SERIAL;
  351. if(serial == null)
  352. serial = "";
  353. return serial;
  354. }
  355. try
  356. {
  357. Method method = Class.forName("android.os.Build").getDeclaredMethod("getString", new Class[] {
  358. Class.forName("java.lang.String")
  359. });
  360. if(!method.isAccessible())
  361. method.setAccessible(true);
  362. serial = (String)method.invoke(new Build(), new Object[] {
  363. "ro.serialno"
  364. });
  365. }
  366. catch(ClassNotFoundException classnotfoundexception)
  367. {
  368. classnotfoundexception.printStackTrace();
  369. return "";
  370. }
  371. catch(NoSuchMethodException nosuchmethodexception)
  372. {
  373. nosuchmethodexception.printStackTrace();
  374. return "";
  375. }
  376. catch(InvocationTargetException invocationtargetexception)
  377. {
  378. invocationtargetexception.printStackTrace();
  379. return "";
  380. }
  381. catch(IllegalAccessException illegalaccessexception)
  382. {
  383. illegalaccessexception.printStackTrace();
  384. return "";
  385. }
  386. return serial;
  387. }
  388. /**
  389. * 反编译 友盟 //手机的唯一标示
  390. * @param context
  391. * @return //机制处理:imei->macAddress->android_id
  392. */
  393. public static String getPhoneId(Context context){
  394. String id = "";
  395. TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  396. if(telephonyManager == null){
  397. Log.e(TAG,"getPhoneId No imei");
  398. }
  399. if(isHasPermission(context,"android.permission.READ_PHONE_STATE")){
  400. id = telephonyManager.getDeviceId();
  401. }
  402. if(TextUtils.isEmpty(id)){
  403. Log.e(TAG,"getPhoneId No imei");
  404. id = getMacAddress(context);
  405. if(TextUtils.isEmpty(id)){
  406. Log.e(TAG, "getPhoneId Failed to take mac as IMEI. Try to use Secure.ANDROID_ID instead.");
  407. id = android.provider.Settings.Secure.getString(context.getContentResolver(), "android_id");
  408. Log.i(TAG, "getDeviceId: Secure.ANDROID_ID: " + id);
  409. return id;
  410. }
  411. }
  412. return id;
  413. }
  414. /**
  415. * 检查 当前包是否具有 指定的权限
  416. * @param context
  417. * @param permissionName 所检查权限的名字
  418. * @return 是否具有此权限
  419. */
  420. public static boolean isHasPermission(Context context,String permissionName){
  421. PackageManager localPackageManager = context.getPackageManager();
  422. if (localPackageManager.checkPermission(permissionName, context.getPackageName()) != PackageManager.PERMISSION_GRANTED ) {
  423. return false;
  424. }
  425. return true;
  426. }
  427. /**
  428. * 获取mac地址
  429. * @param context
  430. * @return
  431. */
  432. public static String getMacAddress(Context context){
  433. try
  434. {
  435. WifiManager localWifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
  436. if (isHasPermission(context, "android.permission.ACCESS_WIFI_STATE")) {
  437. WifiInfo localWifiInfo = localWifiManager.getConnectionInfo();
  438. return localWifiInfo.getMacAddress();
  439. }
  440. Log.e(TAG , "getMacAddress: Could not get mac address.[no permission android.permission.ACCESS_WIFI_STATE");
  441. }
  442. catch (Exception localException) {
  443. Log.e(TAG, "getMacAddress: Could not get mac address." + localException.toString());
  444. }
  445. return "";
  446. }
  447. /**
  448. * 定位 获取当前所在位置信息
  449. * @param context
  450. * @return location
  451. */
  452. public static Location getLocation(Context context){
  453. LocationManager locationManager = null;
  454. try {
  455. locationManager = (LocationManager)context.getSystemService("location");
  456. Location location;
  457. if (isHasPermission(context, "android.permission.ACCESS_FINE_LOCATION"))
  458. {
  459. location = locationManager.getLastKnownLocation("gps");
  460. if (location != null) {
  461. Log.i(TAG, "get location from gps:" + location.getLatitude() + "," + location.getLongitude());
  462. return location;
  463. }
  464. }
  465. if (isHasPermission(context, "android.permission.ACCESS_COARSE_LOCATION"))
  466. {
  467. location = locationManager.getLastKnownLocation("network");
  468. if (location != null) {
  469. Log.i(TAG, "get location from network:" + location.getLatitude() + "," + location.getLongitude());
  470. return location;
  471. }
  472. }
  473. Log.i(TAG, "Could not get location from GPS or Cell-id, lack ACCESS_COARSE_LOCATION or ACCESS_COARSE_LOCATION permission?");
  474. return null;
  475. } catch (Exception localException) {
  476. Log.i(TAG, localException.getMessage());
  477. }
  478. return null;
  479. }
  480. /**
  481. * 是否 网络已连接或正在连接
  482. * @param context
  483. * @return
  484. */
  485. public static boolean isConnectNetwork(Context context){
  486. try
  487. {
  488. ConnectivityManager localConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  489. NetworkInfo Info = localConnectivityManager.getActiveNetworkInfo();
  490. if (Info != null) {
  491. return Info.isConnectedOrConnecting();
  492. }
  493. return false; } catch (Exception localException) {
  494. }
  495. return true;
  496. }
  497. /**
  498. * 是否网络已连接
  499. * @param context
  500. * @return
  501. */
  502. public static boolean isConnectedNetwork(Context context){
  503. try
  504. {
  505. ConnectivityManager localConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  506. NetworkInfo Info = localConnectivityManager.getActiveNetworkInfo();
  507. if (Info != null) {
  508. return Info.isConnected();
  509. }
  510. return false;
  511. } catch (Exception localException) {
  512. }
  513. return false;
  514. }
  515. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/242247
推荐阅读
相关标签
  

闽ICP备14008679号