背景介绍:

到目前为止,android已经从1.5发展到目前的3.2,我们在写一个应用的时候,最常用到得就是获取屏幕高度,宽度,以及status bar的高度。

然而android系统变化太快了,从开始的手机操作系统到目前的3.2 平板电脑系统,在获取这些数据的时候也发生了很大的变化。

值得我们重视,否则会有很多错误发生。


问题分析及解决方案:

1. android 1.6 到 android 2.x

这是android手机操作系统,从1.6到2.x都有着统一的获取方法。

直接利用android api即可获取相关的尺寸,

WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);

int width = wm.getDefaultDisplay().getWidth();//屏幕宽度

int height = wm.getDefaultDisplay().getHeight();//屏幕高度

Rect rect=newRect();

this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

intstatusBarHeight= rect.top; //状态栏高度


2. android 3.0 平板系统

在3.0系统中,status bar在屏幕下方,因为计算方法也发生改变。

在3.0系统中获取屏幕高度和宽度的方法没有改变。

状态的获取方法如下:

Rect rect=newRect();

this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);


int statusBarHeight = window.getWindowManager().getDefaultDisplay().getHeight() - rect.bottom;

即利用屏幕高度减去显示区域的最大高度即为下方status bar的高度


3. android 3.2平板系统

在android 3.2中就有了很大的改变,当我们调用getWidth()和getheight()获取宽度和高度的时候,不会返回屏幕的真实尺寸,

而是只返回屏幕的显示区域的尺寸,即减去了状态栏的高度。

运用这两个api函数读取的尺寸肯定不是我们想要的结果。

这时我们发现其提供了两个隐藏函数getRealHeight()和getRealWidth()用来获取真实的屏幕尺寸。

一因为是隐藏函数,所以我们只能通过反射来调用这两个函数,但这样带来不好的就是反射效率实在是太差了。

Display display = wm.getDefaultDisplay();
Class c = Class.forName("android.view.Display");

Method method = c.getMethod("getRealHeight");
int height = (Integer) method.invoke(display);

Rect rect=newRect();

this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);


statusbarHeight = height - rect.bottom;

对上述代码进行优化,如果当我们频繁调用的时候,必将影响程序性能。

我们可以保存第一次反射的相关信息,然后在后面直接调用。


private Method method = null;// 用来保存method对象

---------------------------------------------------------------------------------

Display display = wm.getDefaultDisplay();

//判断method是否为空,如果为null,则利用反射得到method信息,否则,利用旧的method对象。
if(method == null)
{

method = display.getClass().getMethod("getRealHeight"); //这里直接用display的class信息

}


int height = (Integer) method.invoke(display);

Rect rect=newRect();

this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);













更多相关文章

  1. Android(安卓)如何获取所有的wifi连接历史记录?
  2. Android(安卓)VCard通讯录导入导出详解
  3. Android获取系统的硬件信息、系统版本以及如何检测ROM类型
  4. android 权限详解
  5. android 获取汉字拼音
  6. Android获取外置SD卡读写路径
  7. Android应用如何支持屏幕多尺寸多分辨率问题
  8. Android中可以做的两件坏事---破解锁屏密码和获取Wifi密码
  9. Android的设计尺寸

随机推荐

  1. Android之ListView异步加载图片且仅显示
  2. 【Android】多图选择器(支持图片预览 高
  3. Android(安卓)集成友盟分享 由一个错误的
  4. Android中UI视图之试图绘制机制
  5. 二十一、Android上常见度量单位【xdpi、h
  6. 本科畢業論文——基於Android平臺的零售
  7. 对Android中RecyclerView多选删除的一些
  8. Android(安卓)后台线程及CPU占用
  9. android如何在xml中引用内部类的View
  10. android Ble4.0蓝牙开发之搜索慢、startL