Android性能优化(二)——context 引起的内存问题

本文探讨了Android中四种获取Context的方式:this/getContext(), getApplicationContext(), getBaseContext()和getApplication(),详细解释了它们的区别和使用场景。特别强调了getApplicationContext()在全局数据访问和广播接收器注册中的注意事项,以及如何避免因Context导致的内存泄露,如避免长时间持有Activity的Context,优先使用Application的Context,以及避免在非静态内部类中持有Activity的引用。" 118670166,10207908,深入理解LVS负载均衡技术,"['自动化运维', '负载均衡', 'Linux', '网络', '服务器集群']
摘要由CSDN通过智能技术生成

首先,要搞清楚的是Android中获取上下文的方式:

  1. this 或者 getContext()
  2. getApplicationContext()
  3. getBaseContext()
  4. getApplication()(严格来说,这个方法不能得到程序的Context)

第一种:this or getContext():
谷歌文档给出的解释如下:

Returns the context the view is running in, through which it can access the current theme, resources, etc.
意思是:返回当前Activity的context,通过它可以得到当前的theme,resources等资源。
特点:属于当前Activity,随着当前Activity的销毁而销毁

第二种:getApplicationContext()
谷歌文档给出的解释如下:

Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.

Consider for example how this int

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值