安卓下Application和Activity的Context获取

情形一:Activity中

通过getApplication()获得Application,其本身也是一个的Context,也可以通过getApplicationContext()获得Application的Context,结果一样。

而this表示当前的Activity对象,其本身也是一个的Context。

注意:这两个Context是不一样的,它们的hash code不同。

情形二:Fragment中

通过getActivity()和getContext()得到的是一样的,都是Activity的Context。

情形三:View中

通过getContext()得到的是Activity的Context。


补充:要在Fragement或View中获得Application的Context,先参考"情形二"和"情形三"得到Activity或Activity的Context,再参考"情形一"得到Application的Context。

通过对象的toString方法就能得到对象的描述,形如"com.example.demo.MainActivity@176af1e",这可以用来识别是否为同一对象。

相关推荐
jike_20269 小时前
安卓平台免费录音转文字工具深度测评:5 款 APP 功能对比与选型指南
android·智能电视
Code Man9 小时前
Windows 下使用 Appium
android·windows·appium
码农coding9 小时前
android 12 中的VSYNC接收
android
GitLqr9 小时前
Flutter 3.44 性能飞跃:深度解析 Android Platform View 的 HCPP 新特性
android·flutter·性能优化
码农coding9 小时前
android 12 SurfaceFlinger中的CompositionEngine
android
Mem0rin11 小时前
[MySQL] 聚合函数、分组查询、连接查询
android·mysql
码龙-DragonCoding11 小时前
一键批量提取音频、提取视频
android·音视频·提取
祉猷并茂,雯华若锦11 小时前
Win下完美解决Allure报错,生成Web自动化测试报告
android·python·selenium·自动化
IT小盘13 小时前
08-FastAPI加MySQL实现AI对话记录持久化
android·mysql·fastapi
alice--小文子13 小时前
安卓(Android)- 怎么在adb中通过真机操作日志相关
android·adb