开发者

android: Service vs SingleTop Activity moved to background - whats the difference?

开发者 https://www.devze.com 2023-03-22 15:11 出处:网络
im currently developing an app which plays the steam audio using MediaPlayer class. And i\'d declare its main (Player) activity as SingleTop. Also on button \"Back\" it does moveTaskToBack(true) whic

im currently developing an app which plays the steam audio using MediaPlayer class. And i'd declare its main (Player) activity as SingleTop. Also on button "Back" it does moveTaskToBack(true) which acts the same as button Home does. So it just stays and plays on background and if user wants to see the gui he just starts the app once again (which is less convenient) or he clicks the special app's notify. Exit provided via menu.

but what are th开发者_如何学编程e benefits of using service instead of activity in such case? Definitely it would be more complex to develop, i have to say. Even instantiating the GUI while "on background" will take much more time, i'm afraid.


From the Android Documentation:

Activities An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails.

Services A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it.

also

Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.

The Android OS can destroy your Activity if it runs out of resources, but it won't destroy the service.

EDIT: you should use startForeground() to ensure your Service won't be killed in situations where the resources are low. From the docs:

Make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You can set this flag if killing your service would be disruptive to the user, such as if your service is performing background music playback, so the user would notice if their music stopped playing.

0

精彩评论

暂无评论...
验证码 换一张
取 消