android设备信息获取处理
计算设备尺寸:
public static double getScreenPhysicalSize(Activity ctx) {
DisplayMetrics dm = new DisplayMetrics();
ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);
double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));
return diagonalPixels / (160 * dm.density);
}
判断设备是否为平板
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
获取mac
public static String getDeviceMac(Context appContext){
String macAddress = null ;
WifiManager wifiManager =
(WifiManager)appContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = ( null == wifiManager ? null : wifiManager.getConnectionInfo());
if (!wifiManager.isWifiEnabled()){//必须先打开,才能获取到MAC地址
wifiManager.setWifiEnabled(true);
}
if (null != info) {
macAddress = info.getMacAddress();
}
if(!TextUtils.isEmpty(macAddress) && false==macAddress.startsWith("02:00:00"))
return macAddress;
//解决部分机型关闭wifi时,获取到02:00:00 mac不准确
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:",b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "02:00:00:00:00:01";
}
android 获取设备型号、OS版本号:
Build bd = new Build();
String model = bd.MODEL;
android.os.Build.MODEL
android.os.Build.SERIAL;
android.os.Build.VERSION.RELEASE
获取系统语言环境:
Locale.getDefault().getLanguage();
language=Locale.getDefault().toString();//en_US zh_CN
获取状态栏和标题栏的高度
获取状态栏高度:
getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
于是,我们就可以算出状态栏的高度了。
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
获取标题栏高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight
通过反射机制获取通知栏高度
public static int getStatusBarHeight(Context context){
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, statusBarHeight = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
屏幕分辨率
private void initDisplayMetrics(){
DisplayMetrics dm=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
this.width=dm.widthPixels;
this.height=dm.heightPixels;
}
屏幕密度相关
//https://developer.android.google.cn/guide/practices/screens_support.html
void testShowDeviceInfo(){
Resources res = getResources();
DisplayMetrics displayMetrics = res.getDisplayMetrics();
int density = displayMetrics.densityDpi;//屏幕密度
int sw = res.getConfiguration().smallestScreenWidthDp;//适配最小横向dp值(例如:layout-sw600dp)
//Get the screen's density scale
float scale = displayMetrics.density;//屏幕拉伸比例系数
StringBuilder buf = new StringBuilder();
buf.append("scale factor:").append(scale).append(" smallest screen size:").append(sw)
.append(" current densityDpi:").append(density).append(" width x height:")
.append(displayMetrics.widthPixels).append(" x ").append(displayMetrics.heightPixels);
TextView tvTitle = findViewById(R.id.tvHeadLine);
tvTitle.setText(buf.toString());
switch (density) {//密度对应资源匹配
case DisplayMetrics.DENSITY_MEDIUM:
break;
case DisplayMetrics.DENSITY_HIGH:
break;
case DisplayMetrics.DENSITY_TV:
break;
case DisplayMetrics.DENSITY_XHIGH:
break;
case DisplayMetrics.DENSITY_XXHIGH:
break;
case DisplayMetrics.DENSITY_XXXHIGH:
break;
}
}
获取内存信息:
ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(outInfo);
//可用内存
outInfo.availMem
//是否在低内存状态
outInfo.lowMemory
使用Java获取系统内存信息;
void memery(){
String m1=(Runtime.getRuntime().maxMemory()/ (1024 * 1024)) + "MB" ;
String m2=(Runtime.getRuntime().totalMemory()/ (1024 * 1024)) + "MB" ;
String m3=(Runtime.getRuntime().freeMemory()/ (1024 * 1024)) + "MB" ;
System.out.println("MaxMemory= "+m1+" totalMemory= "+m2+" freeMemory= "+m3);
}
ActivityManager mActManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
/** 获得系统正在运行的进程. */
List<RunningAppProcessInfo> mAllSysAppProcesses = mActManager.getRunningAppProcesses();
获取设备ip地址字符串形式表示
public String getLocalIpAddress() {
String strIP=null;
try {
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()) {
strIP= inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("msg", ex.toString());
}
return strIP;
}
获取Android设备的唯一识别码。由于设备杂乱,为了保证设备号唯一性,可以采用获取UUID方式。
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, tmPhone, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
String uniqueId = deviceUuid.toString();
所有的设备都可以返回一个 TelephonyManager.getDeviceId()
所有的GSM设备 (测试设备都装载有SIM卡) 可以返回一个TelephonyManager.getSimSerialNumber()
所有的CDMA 设备对于 getSimSerialNumber() 却返回一个空值!
所有添加有谷歌账户的设备可以返回一个 ANDROID_ID
所有的CDMA设备对于 ANDROID_ID 和 TelephonyManager.getDeviceId() 返回相同的值(只要在设置时添加了谷歌账户)
//获取电池电量:
Intent batteryIntent = getApplicationContext().registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int currLevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int total = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
int percent = currLevel * 100 / total;
//或者
private BroadcastReceiver batteryReceiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra("level", 0);
// level加%就是当前电量了
}
};
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
//开机时间:
private String getOpenDeviceTimes() {
long ut = SystemClock.elapsedRealtime() / 1000;
if (ut == 0) {
ut = 1;
}
int m = (int) ((ut / 60) % 60);
int h = (int) ((ut / 3600));
return h + " " + mContext.getString(R.string.info_times_hour) + m + " "
+ mContext.getString(R.string.info_times_minute);
}
获取CPU信息:
/proc/cpuinfo文件中第一行是CPU的型号,第二行是CPU的频率
public String[] getCpuInfo() {
String str1 = "/proc/cpuinfo";
String str2="";
String[] cpuInfo={"",""};
String[] arrayOfString;
try {
FileReader fr = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("\\s+");
for (int i = 2; i < arrayOfString.length; i++) {
cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
}
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("\\s+");
cpuInfo[1] += arrayOfString[2];
localBufferedReader.close();
} catch (IOException e) {
}
return cpuInfo;
}
获取simCard相关:
/**
* Role:获取当前设置的电话号码
* <BR>Date:2012-3-12
* <BR>@author CODYY)peijiangping
*/
public String getNativePhoneNumber() {
String NativePhoneNumber=null;
NativePhoneNumber=telephonyManager.getLine1Number();
return NativePhoneNumber;
}
/**
* Role:Telecom service providers获取手机服务商信息 <BR>
* 需要加入权限<uses-permission
* android:name="android.permission.READ_PHONE_STATE"/> <BR>
* Date:2012-3-12 <BR>
*
* @author CODYY)peijiangping
*/
public String getProvidersName() {
String ProvidersName = null;
// 返回唯一的用户ID;就是这张卡的编号神马的
IMSI = telephonyManager.getSubscriberId();
// IMSI号前面3位460是国家,紧接着后面2位00 02是中国移动,01是中国联通,03是中国电信。
System.out.println(IMSI);
if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
ProvidersName = "中国移动";
} else if (IMSI.startsWith("46001")) {
ProvidersName = "中国联通";
} else if (IMSI.startsWith("46003")) {
ProvidersName = "中国电信";
}
return ProvidersName;
}
获取存储可用空间:
private static final double KB = 1024.0;
private static final double MB = KB * KB;
private static final double GB = KB * KB * KB;
private static String showFileSize(double size) {
String fileSize;
if (size < KB)
fileSize = size + "B";
else if (size < MB)
fileSize = String.format("%.3f", size / KB) + "KB";
else if (size < GB)
fileSize = String.format("%.3f", size / MB) + "MB";
else
fileSize = String.format("%.3f", size / GB) + "GB";
return fileSize;
}
/** 显示SD卡剩余空间 */
public static String getSdcardAvailable() {
String result = "";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
StatFs sf = new StatFs("/mnt/sdcard");
long blockSize = sf.getBlockSize();
long blockCount = sf.getBlockCount();
long availCount = sf.getAvailableBlocks();
return showFileSize(availCount * blockSize) + " \\ " + showFileSize(blockSize * blockCount);
}
return result;
}
/**
* 获取手机内部可用空间大小
* @return
*/
static public long getAvailableInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
/**
* 获取手机内部空间大小
* @return
*/
static public long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
获取内存使用情况:
public static String getMemoryUsage() {
ActivityManager activityManager = (ActivityManager) DscaApplication.AppContext.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
long availMemory = memoryInfo.availMem / ONE_M_TO_BYTE;
long totalMemory = memoryInfo.totalMem / ONE_M_TO_BYTE;
return availMemory + "M/" + totalMemory + "M";
}

浙公网安备 33010602011771号