java Activity.getIntent() 可以返回 null 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37856407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:53:39  来源:igfitidea点击:

Can Activity.getIntent() ever return null?

javaandroidandroid-intent

提问by Armand

Can Activity.getIntent()ever return null?

Activity.getIntent()回来null吗?

The documentation does not mention this as a possibility, so I am wondering if I have to check the result of getIntent()for nullvalue before dereferencing it.

文档没有提到这种可能性,所以我想知道在取消引用之前是否必须检查getIntent()for nullvalue的结果。

回答by Kirill

Yes, it can, but only in two cases:

是的,它可以,但仅限于两种情况:

In activity constructor:
Intent set up in internal attachmethod, called from Instrumentationclass:

在活动构造函数中:
在内部attach方法中设置的意图,从Instrumentation类调用:

public Activity newActivity(Class<?> clazz, Context context, 
        IBinder token, Application application, Intent intent, ActivityInfo info, 
        CharSequence title, Activity parent, String id,
        Object lastNonConfigurationInstance) throws InstantiationException, 
        IllegalAccessException {
    Activity activity = (Activity)clazz.newInstance();
    ActivityThread aThread = null;
    activity.attach(context, aThread, this, token, 0, application, intent,
            info, title, parent, id,
            (Activity.NonConfigurationInstances)lastNonConfigurationInstance,
            new Configuration(), null, null);
    return activity;
}

therefore intent is always null in constructor.

因此意图在构造函数中始终为空。

After setIntent(null):
It's possible to change intent from outside of activity with setIntent().

在 setIntent(null) 之后:
可以使用setIntent().

In all other cases it can't.

在所有其他情况下,它不能。

回答by RelaxedSoul

It CAN be null when Your application was updated from the market while it was in the memory and relaunched again after the update. Maybe even If you will make update manually by Studio, or from .apk file, the same effect will be. Not sure, sorry.

当您的应用程序在内存中从市场更新并在更新后再次重新启动时,它可以为空。也许即使您将通过 Studio 或从 .apk 文件手动进行更新,也会产生相同的效果。不确定,抱歉。

I once updated application in Google Dev console and got several different NPE in Crashlitics in the lines with call getIntent(). It happened for all screens, where I used getIntent().getExtra() onCreate or even later in lifeCycle.

我曾经在 Google Dev 控制台中更新了应用程序,并在调用 getIntent() 的行中在 Crashlitics 中获得了几个不同的 NPE。它发生在所有屏幕上,我使用 getIntent().getExtra() onCreate 甚至生命周期的后期。

So... It looks ugly, but to avoid crashes I need to check intent for NULL value all the time I call getIntent and most of the times I call Finish() if the intent is null. But you can make other logic, ofc, for you purpose.

所以......它看起来很丑,但为了避免崩溃,我需要在调用 getIntent 时检查 NULL 值的意图,并且大多数时候如果意图为空,我会调用 Finish()。但是您可以为您的目的创建其他逻辑。