您可以使用DisplayMetrics获取有关您的应用程序在其上运行的屏幕的大量信息。
首先,我们创建一个DisplayMetrics规格对象:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int wwidth = displaymetrics.widthPixels;
这将返回的宽度的绝对值和以像素为单位的高度,所以1280×720为银河SIII,银河的Nexus等
这通常不会对我们有帮助,因为当我们在Android设备上工作时,我们通常更喜欢使用密度独立像素,倾角。
float scaleFactor = displaymetrics .density;
从这个结果,我们可以计算出一定高度或宽度的密度独立像素的数量。
float widthDp = widthPixels/scaleFactor
float heightDp = heightPixels/scaleFactor
使用上述信息,我们知道,如果该装置的最小宽度是小于600dp更大,该装置是一个7" 片剂,如果它比720dp更大,该装置是一个10" 片剂。
我们可以使用Math类的min函数计算出最小宽度,传递heightDp和widthDp以返回最小宽度。
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
//Device is a 10" tablet
}
else if (smallestWidth > 600) {
//Device is a 7" tablet
}
然而,这并不总是给你一个确切的匹配,特别是可能被歪曲的密度,华电国际,当它不晦涩片工作时,或可能仅是800×480像素,但仍然在7英寸屏幕上
除了这些方法,如果您需要知道以英寸为单位的设备的确切尺寸,您也可以使用度量方法了解每个设备的像素数量屏幕的英寸。
float widthDpi = displaymetrics .xdpi;
float heightDpi = displaymetrics .ydpi;
您可以使用有关每英寸设备中有多少像素以及总共有多少像素来计算设备的英寸数的知识。
float widthInches = widthPixels/widthDpi;
float heightInches = heightPixels/heightDpi;
这将以英寸返回设备的高度和宽度。这又不一定有助于确定它是什么类型的设备,因为设备的广告尺寸是对角线,我们只有高度和宽度。
但是,我们也知道,给定三角形的高度和宽度,我们可以使用毕达哥拉斯定理来计算斜边的长度(在这种情况下,屏幕对角线的大小)。
//a² + b² = c²
//The size of the diagonal in inches is equal to the square root of the height in inches squared plus the width in inches squared.
double diagonalInches = Math.sqrt(
(widthInches * widthInches)
+ (heightInches * heightInches));
从这一点,我们可以计算出该设备是平板电脑或不:
if (diagonalInches >= 10) {
//Device is a 10" tablet
}
else if (diagonalInches >= 7) {
//Device is a 7" tablet
}
三江源,你在这里写了一个很好的答案描述,是非常有帮助! – ViVekH
乐于帮助。享受编码 –