getApplicationContext 返回 null 原因及解决方案

博客介绍了getApplicationContext返回null的原因及解决方案。原因是mApplication在attachBaseContext方法调用后才赋值,若在Application的onBaseContextAttached生命周期方法中使用Context,getApplicationContext会返回null。解决方案是将相关代码从onBaseContextAttached移到onCreate中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

getApplicationContext 返回 null 原因及解决方案

Get application context returns null.

原因

从下面可知 mApplication 在 attachBaseContext 方法被调用之后才被赋值

final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
        attachBaseContext(context);
        .......
        mApplication = application;
        }

因此,如果在 Application 的 onBaseContextAttached 生命周期方法中使用 Contex ,则不能调用 getApplicationContext 方法。因为,此时 mApplication 还没有被赋值,getApplicationContext 也就是返回 null。

public void onBaseContextAttached(Context base) 

解决方案

将你可能需要使用到 Application 或者 Context (可能调用 onBaseContextAttached)的代码,从 onBaseContextAttached 移动到 Application 生命周期方法 onCreate 中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值