android context

在android中context可以作很多操作,但是最主要的功能加载 和访问资源 。在android中有两种context,一种是 application context,一种是activity context,通常我们在各种类和方法间传递的是activity context。
比如一个activity的onCreate:
protected void onCreate(Bundle state) {
super.onCreate(state);

TextView label = new TextView(this); //传递context给view control
label.setText("Leaks are bad");

setContentView(label);
}
把activity context传递给view,意味着view拥有一个指向activity的引用,进而引用activity占有的资源:view hierachy, resource等。
这样如果context发生内存 泄露的话,就会泄露很多内存。
这里泄露的意思是gc没有办法回收activity的内存。

Leaking an entire activity是很容易的一件事。

屏幕 旋转的时候,系统 会销毁当前的activity,保存状态 信息,再创建一个新的。

比如我们写了一个应用 程序 ,它需要加载一个很大的图片,我们不希望每次旋转屏 幕的时候都销毁这个图片,重新加载。实现这个要求的简单想法就是定义 一个静态的Drawable,这样Activity 类创建销毁它始终保存在内存中。
实现类似:
public class myactivity extends Activity {
private static Drawable sBackground;
protected void onCreate(Bundle state) {
super.onCreate(state);

TextView label = new TextView(this);
label.setText("Leaks are bad");

if (sBackground == null) {
sBackground = getDrawable(R.drawable.large_bitmap);
}
label.setBackgroundDrawable(sBackground);//drawable attached to a view

setContentView(label);
}
}
这段程序看起来很简单,但是却问题很大。当屏幕旋转的时候会有leak(即gc没法销毁activity)。
我 们刚才说过,屏幕旋转的时候系统会销毁当前的activity。但是当drawable和view关联后,drawable保存了view的 reference,即sBackground保存了label的引用,而label保存了activity的引用。既然drawable不能销毁,它所 引用和间接引用的都不能销毁,这样系统就没有办法销毁当前的activity,于是造成了内存泄露。gc对这种类型的内存泄露是无能为力的。

避免这种内存泄露的方法是避免activity中的任何对象 的 生命周期长过activity,避免由于对象对 activity的引用导致activity不能正常被销毁。我们可以使用application context。application context伴随application的一生,与activity的生命周期无关。application context可以通过Context.getApplicationContext或者Activity.getApplication方法获取

避免context相关的内存泄露,记住以下几点:
1. 不要让生命周期长的对象引用activity context,即保证引用activity的对象要与activity本身生命周期是一样的
2. 对于生命周期长的对象,可以使用application context
3. 避免非静态的内部类,尽量使用静态类,避免生命周期问题,注意内部类对外部对象引用导致的生命周期变化

更多相关文章

  1. Android程序优化之对屏幕旋转的处理总结
  2. 从android游戏框架看其生命周期
  3. Android中解决手机屏幕横竖屏切换问题
  4. android context
  5. 【引用】Android的CTS测试
  6. 2020-Android面试
  7. Android(安卓)Context
  8. android 格式化
  9. android context理解

随机推荐

  1. android 动态设置控件大小
  2. android 文件保存方法 sd卡中或系统
  3. android dialog使用小结
  4. 检测android机器是否有GPS模块
  5. Android(安卓)图片缩放,图片圆角处理
  6. android 常用代码
  7. android Rect的使用
  8. 【Android代码片段之三】TabActivity实现
  9. Android(安卓)百度地图-实现POI的搜索(搜
  10. android O 手机关机流程与时间