Starting Service in Android calls Applications onCreate

有些话、适合烂在心里 提交于 2020-01-11 09:13:46

问题


I am starting an android service using,

startService(getApplicationContext(), MyService.class);

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

Case 1: Calling above code from Application onCreate()

  • I see that Application.onCreate() gets called two time. One is the desired App create and other happens when startService is called.

Case 2: Calling above code from Activity in application

  • Same behavior as case 1.

Is this intended behavior?

My Android Manifest Code as requested:

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

回答1:


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.)

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.

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.

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.



来源:https://stackoverflow.com/questions/30315165/starting-service-in-android-calls-applications-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!