Android中的启动服务在onCreate上调用应用程序 [英] Starting Service in Android calls Applications onCreate

查看:195
本文介绍了Android中的启动服务在onCreate上调用应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来启动android服务

I am starting an android service using,

startService(getApplicationContext(), MyService.class);

我已经在AndroidManifest中正确定义了我的服务.现在,我从Application create调用上面的代码.

I have correctly defined my service in AndroidManifest. Now, I am calling above code from Application create.

情况1:从应用程序onCreate()调用上述代码

Case 1: Calling above code from Application onCreate()

  • 我看到Application.onCreate()被调用了两次.一种是所需的应用程序创建,另一种是在调用startService时发生.

情况2:在应用程序的Activity中调用上述代码

Case 2: Calling above code from Activity in application

  • 行为与情况1相同.

这是预期的行为吗?

我的Android清单代码要求:

My Android Manifest Code as requested:

    <service
            android:exported="false"
            android:enabled="true"
            android:name=".MyService"
            android:process=".MyService">
    </service>

推荐答案

由于您在<service>元素中指定了android:process属性,并且其值与应用程序包名称不同,因此该服务实际上正在运行与应用程序的默认流程分开的流程. (我不知道这是否是故意的,但您似乎在进程名称中也有错字.)

Since you specified the android:process attribute in your <service> element, and its value is not the same as your application package name, that service is actually running in a separate process from the default process for your application. (I don't know if it was intentional, but you also seem to have a typo in the process name.)

如果您不打算在单独的进程中运行该服务(这种情况很少见,并且只有在有充分的理由并且了解其含义的情况下才应该执行),您应该在自己的代码中省略android:process属性<service>元素-这将导致它与应用程序其余部分的运行过程相同.

If you did not intend to run the service in a separate process (which is rare, and something you should only do if you have a good reason and understand the implications), you should just omit the android:process attribute in your <service> element -- this would cause it to run in the same process as the rest of your app.

Android鲜为人知且似乎未记录的行为是应用程序的每个进程都有自己的Application实例.这说明了为什么启动服务会创建一个附加的Application实例.

A little-known and seemingly undocumented behavior of Android is that each process of an application has is own Application instance. This explains why starting your service created an additional Application instance.

此外,这两个进程不仅具有自己的Application实例,而且实际上具有自己的Application类,因为它们甚至不共享相同的类加载器.因此,即使它们的静态变量也可以具有不同的值.

Also, not only do the 2 processes have their own Application instances, they actually have their own Application classes, since they do not even share the same class loaders. Therefore, even their static variables can have different values.

这篇关于Android中的启动服务在onCreate上调用应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆