Android 中的两个 onCreate() 方法?
我正在研究另一个示例(在这里找到 将 MP3 加载到声音池中安卓)。但由于某种原因,我最终得到了两个 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);
}
}
I am working off another example (found here Loading MP3s into the Sound Pool in Android). but for some reason I am ending up with two onCreate()
methods and if I delete one I am getting errors.
I am trying to load the MP3s into the Soundpool once and then call them in other activities.
My code:
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码中每个类只有一个
onCreate
方法。它们有不同的用途,并在操作系统创建每个类时被调用。创建应用程序时会调用
MyApp.onCreate
并在MyApp
类中设置应用程序范围的状态。创建 Activity 时会调用
TestAndroidGlobalsActivity.onCreate
并设置该特定 Activity 的状态并初始化其 UI。Your code only has one
onCreate
method per class. They serve different purposes and are called when each of those classes is created by the OS.Your
MyApp.onCreate
is called when the application is created and sets up application-wide state inside yourMyApp
class.Your
TestAndroidGlobalsActivity.onCreate
is called when the Activity is created and sets the state for that specific activity an initializes its UI.您不能混淆 Application.onCreate(在创建应用程序时调用)和 Activity.onCreate(在每次调用 Activity 时调用)(在一个应用程序执行期间可能会发生多次)
此外,您应该在每个覆盖上方添加 @Override 注释方法。
you must not confuse Application.onCreate, called when your application is created, and Activity.onCreate, called every time your activity is called (which may happen several times during one application execution)
Also, you should have the @Override annotation above each overriden method.