Android中有两个onCreate()方法?

时间:2011-08-16 14:20:20

标签: inner-classes soundpool android

我正在处理另一个例子(在Loading MP3s into the Sound Pool in Android找到)。但出于某种原因,我最终得到了两个onCreate()方法,如果我删除了一个,我就会收到错误。

我正在尝试将MP3加载到Soundpool中,然后在其他活动中调用它们。

我的代码:

class MyApp extends Application {
    private static MyApp singleton;

    private static SoundPool mSoundPool;

    public onCreate() { // ##### Deleting this gives me errors ###, not deleting it gives me 1 error.
         super.onCreate();
         singleton = this;
         mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);// Just an example
    }

    public static MyApp getInstance() {
         return singleton;
    }

    public SoundPool getSoundPool() {
         return mSoundPool;
    }
}


public class TestAndroidGlobalsActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

2 个答案:

答案 0 :(得分:3)

您的代码每个类只有一个onCreate方法。它们用于不同的目的,并在操作系统创建每个类时调用。

创建应用程序时调用MyApp.onCreate,并在MyApp类中设置应用程序范围的状态。

创建活动时调用TestAndroidGlobalsActivity.onCreate并设置该特定活动的状态并初始化其UI。

答案 1 :(得分:1)

你不能混淆在创建应用程序时调用的Application.onCreate和每次调用活动时调用的Activity.onCreate(在一次应用程序执行期间可能会多次调用)

此外,您应该在每个覆盖方法上面都有@Override注释。