简体   繁体   English

将服务附加并实例化到Application.java

[英]Attach and instantiate Service into Application.java

I am trying attach and instantiate a variable that is a Service, before start the first Activity. 我尝试在启动第一个Activity之前附加并实例化一个作为Service的变量。

I am trying this: 我正在尝试:

Application.java 应用程序

public class ApplicationBase extends Application {

    public ServiceDoSport mServiceDoSport;

    @Override
    public void onCreate() {

        startService(new Intent(this, ServiceDoSport.class));
        super.onCreate();
    }

}

ServiceDoSport.java: ServiceDoSport.java:

public class ServiceDoSport extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // attach service to main application
        ApplicationBase mApplication = (ApplicationBase) getApplication();
        mApplication.mServiceDoSport = this;
    }
}

But the onCreate method of the first Activity is called before than Service has been attached and instantiated to ApplicationBase. 但是,在Service已附加并实例化到ApplicationBase之前,将调用第一个Activity的onCreate方法。

How I can do this? 我该怎么做?

What I doing wrong? 我做错了什么?

I am trying attach and instantiate a variable that is a Service, before start the first Activity 我在开始第一个Activity之前尝试附加并实例化一个作为Service的变量。

You cannot guarantee that will happen. 您不能保证会发生这种情况。 startService() is asynchronous, and you have no way to guarantee that it will start before an activity does. startService()是异步的,您无法保证它将在活动之前启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM