Within an application, will the activity and servi

2020-06-19 07:16发布

Interview Question : With in an Application, will the Activity and Service run in the same process or different processes? My Answer was ::: In the same process.

Next Question ::: If so, how is that the Activity and Service run at the same time? My Answer was ::: Operating System will take care of the execution. (Frankly, I didn't knew the answer).

Can someone give an explanation of the above questions? If my answer was wrong, what is the correct answer?

3条回答
手持菜刀,她持情操
2楼-- · 2020-06-19 07:53

they can both work in same or different processes depending on customization. and yes, OS is the responsible for execution of these two. check this for detailed explanation: http://developer.android.com/guide/topics/manifest/service-element.html#proc

查看更多
可以哭但决不认输i
3楼-- · 2020-06-19 07:58

There is no way to start an Activity and a Service that run in the same process (which is the default behaviour) at the same time.

The onCreate() method of the Service runs on the main (UI) thread.

The onCreate() method of the Activity also runs on the main (UI) thread.

The only way to have both start at more-or-less the same time is to have the Service run in a separate process.

You can try to launch few threads and use semaphore with barier flag.

查看更多
不美不萌又怎样
4楼-- · 2020-06-19 07:59

If service and activity belongs to your app then:

Same process if not defined otherwise. You can create service that will run in separate process.

Service and Activity share same thread. So they can't run simultaneously. But you can create new threads to process commands in Service. Or use IntentService that processes all commands in own thread. Some Service methods always executed on UI thread (e.g. onCreate) Then activity and service can run in parallel (if you have 2 and more cores =).

查看更多
登录 后发表回答