什么时候调用Application的onCreate()方法? [英] When does Application's onCreate() method get called?
问题描述
在我的Android应用程序中,我有一个DefaultApplication
类扩展了android.app.Application
,在其onCreate()
中,我绑定了一些服务,这些服务将由该应用程序中的其他活动使用.
In my Android application, I have a DefaultApplication
class which extends android.app.Application
, and in its onCreate()
I bind some services which will be used by my other Activities in this app.
我还有一个BroadcastReceiver
,它监听和接收C2DM消息.当接收方在应用程序未运行时收到消息时,它将触发一个对话框,其中显示即将出现的消息,并将启动我的应用程序的活动.
Also I have a BroadcastReceiver
which listens and receives C2DM Messages. When this receiver receives a message when the application is not running, it will fire a dialog which shows the upcoming message and it will start an Activity of my application.
我的问题是,当我在不与DefaultApplication
进行任何交互的情况下启动活动时,由于该应用程序的活动已启动,我的DefaultApplication
的onCreate()
是否会被调用?
My question is, when I start an activity without any interaction with DefaultApplication
, will my DefaultApplication
's onCreate()
get called because an Activity of that application has started?
这是我的DefaultApplication
的定义和清单:
Here are the definition and Manifest of my DefaultApplication
:
public class DefaultApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
doBindService();
}
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(DefaultApplication.this, SocketService.class),
socketServiceConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(socketServiceConnection);
mIsBound = false;
}
}
}
清单看起来像这样:
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:name="com.mypackage.DefaultApplication"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:debuggable="true">
<service android:name="com.mypackage.services.SocketService"></service>
<activity android:name="TestActivity"
android:screenOrientation="landscape"></activity>
</application>
推荐答案
只有第一次.
启动Activity且未加载应用程序时,将同时调用两个onCreate()
方法.
When Activity is started and application is not loaded, then both onCreate()
methods will be called.
但是对于后续的Activity启动,将不会调用应用程序的onCreate()
.
But for subsequent starts of Activity, the onCreate()
of application will not be called.
这篇关于什么时候调用Application的onCreate()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!