浅谈Service

来源:互联网 发布:程序员有哪些考试 编辑:程序博客网 时间:2024/05/21 07:00

1.Start一个Service的状态是:首次Start:onCreate--》OnStartCommand--》OnStart(已废弃)

                                              非首次Start:OnStartCommand--》OnStart(已废弃)

    Stop一个Service的状态是:OnDestory()

2.Service与主线程是处于同一个线程中;

 

 

Should you use a service or a thread?
A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

译文:
什么时候使用Service还是线程?
service是一个可以在后台运行的组件,即使当用户不在与应用程序交互。因此,当你需要时,你可以可以创建一个service;

但是,当用户与程序交互是,而需要在主线程之外执行一些操作,这时候应该创建一个新线程而不是一个service。

举个例子,播放音乐,当只是需要在activity运行时播放,这时候可以在activity的onCreate()方法中创建一个线程,播放的方法放在activity的onStart()中,停止的方法放在activity的onStop()中。当然在这里还可以考虑使用AsyncTask 或HandlerThread,而不是简单的使用一个线程类。(注:异步任务和HandlerThread都是新起一个线程完成一些任务)

记住:线程模式是运行在程序的主线程中,所以,在需要完成一系列或阻塞操作时,应该在service创建一个新的线程。
还有一个IntentService:
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.

 

0 0
原创粉丝点击