super.onCreate(savedInstanceState);

问题描述 投票:80回答:4

我创建了一个Android应用程序项目,在MainActivity.java> onCreate()中调用super.onCreate(savedInstanceState)

作为初学者,任何人都可以解释上述行的目的是什么?

android instance super oncreate
4个回答
146
投票

您创建的每个Activity都是通过一系列方法调用启动的。 onCreate()是这些电话中的第一个。

您的每个活动都直接或通过继承android.app.Activity的另一个子类来扩展Activity

在Java中,当您从类继承时,可以覆盖其方法以在其中运行您自己的代码。一个非常常见的例子是在扩展toString()时覆盖java.lang.Object方法。

当我们覆盖一个方法时,我们可以选择完全替换我们类中的方法,或者扩展现有的父类方法。通过调用super.onCreate(savedInstanceState);,除了父类的onCreate()中的现有代码之外,还要告诉Dalvik VM运行代码。如果省略此行,则只运行您的代码。完全忽略现有代码。

但是,您必须在方法中包含此超级调用,因为如果不这样,那么onCreate()中的Activity代码永远不会运行,并且您的应用程序将遇到各种问题,例如没有为活动分配上下文(尽管你'在你有机会弄清楚你没有上下文之前会打一个SuperNotCalledException)。

简而言之,Android自己的类可能非常复杂。框架类中的代码处理UI绘图,房屋清理以及维护活动和应用程序生命周期等内容。 super调用允许开发人员在幕后运行这个复杂的代码,同时仍然为我们自己的应用程序提供良好的抽象级别。


4
投票

*派生类onCreate(bundle)方法必须调用此方法的超类实现。如果未使用“super”关键字,它将抛出异常SuperNotCalledException。

对于Java中的继承,要覆盖超类方法并执行上面的类方法,请在重写派生类方法中使用super.methodname();

Android类的工作方式相同。通过扩展Activity类,其中有onCreate(Bundle bundle)方法,其中编写有意义的代码并在定义的活动中执行该代码,使用super关键字和onCreate()方法,如super.onCreate(bundle)

这是用Activity类onCreate()方法编写的代码,Android Dev团队可能会在以后为此方法添加一些更有意义的代码。因此,为了反映添加内容,您应该在Activity类中调用super.onCreate()。

protected void  onCreate(Bundle savedInstanceState) {
    mVisibleFromClient = mWindow.getWindowStyle().getBoolean(
    com.android.internal.R.styleable.Window_windowNoDisplay, true);
    mCalled = true;
}

boolean mVisibleFromClient = true;

/**
 * Controls whether this activity main window is visible.  This is intended
 * only for the special case of an activity that is not going to show a
 * UI itself, but can't just finish prior to onResume() because it needs
 * to wait for a service binding or such.  Setting this to false prevents the UI from being shown during that time.
 * 
 * <p>The default value for this is taken from the
 * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme.
 */

它还维护变量mCalled,这意味着您已在Activity中调用super.onCreate(savedBundleInstance)

final void performStart() {
    mCalled = false;
    mInstrumentation.callActivityOnStart(this);
    if (!mCalled) {
        throw new SuperNotCalledException(
            "Activity " + mComponent.toShortString() +
            " did not call through to super.onStart()");
    }
}

请在此处查看源代码。

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/app/Activity.java#Activity.onCreate%28android.os.Bundle%29


1
投票

因为在super.onCreate()它会到达Activity(任何活动的父类)类来加载savedInstanceState,而我们通常不设置任何保存的实例状态,但是android框架做了这样的方式,我们应该调用那。


1
投票

如果由于某些隐含原因(例如,不是因为用户按下后退按钮而导致活动被销毁并重新启动),那么您希望通过onCreate()返回到您的应用程序的信息。 onSaveInstanceState()最常见的用途是处理屏幕旋转,因为默认情况下,当用户滑出G1键盘时,活动会被销毁并重新创建。

调用super.onCreate(savedInstanceState)的原因是因为您的代码不会编译。 ;-)

© www.soinside.com 2019 - 2024. All rights reserved.