您的位置:首页 > 移动开发 > Android开发

Android开发之浅谈Service的基本概况和常见问题

2014-04-06 17:00 483 查看
    Service(服务)是一个应用程序组件,可以在后台执行长时间运行的操作,不提供用户界面。其他应用程序组件可以启动一个Serivce,它将继续在后台运行,即使用户切换到另一个应用程序。此外,一个组件可以绑定到一个服务与它交互,甚至执行进程间通信(IPC)。例如,一个Serivice可能处理网络交易,播放音乐,执行文件I / O,或与一个内容提供者交互,所有的背景。

   Serivice运行在哪里呢,这是一个常见的问题。Service在默认情况下运行在主线程的托管进程(当它不创建自己的线程和不运行在一个单独的进程)。这又意为着什么呢,,如果您的服务将做任何CPU密集型工作或阻塞操作(如MP3播放或网络),您应该创建一个新线程内的服务工作。通过使用一个单独的线程,您将减少风险的应用程序没有响应”(ANR)错误和应用程序的主线程可以仍然致力于用户交互活动,可以进行UI的交互。

   什么时候应该使用Service而什么时候应该使用线程(Thread)呢,Service是一个简单的组件,可以在后台运行,即使用户没有与应用程序交互,它也可以运行,因此,您如果创建一个service的情况应该是只用它运行就好不用于界面交互。

   如果您需要执行工作在你的主线程外,但只有在用户与应用程序交互中运行,那么你应该而不是创建一个新的线程,而不是Service。例如,如果你想播放一些音乐,但只有当你的活动正在运行,您可以创建一个线程在onCreate(),在onStart()开始运行它,然后停止在onStop()。也可以考虑使用AsyncTask或HandlerThread,而不是传统的线程类。

    Service自己会关闭吗?当启动一个Service,它有一个独立的生命周期开始它的组件和服务可以无限期地在后台运行,即使开始它的组件被摧毁。因此,Service应该停止本身当它的工作是通过调用stopSelf(),或者另一个组件可以阻止它通过调用stopService()。

    Service跟一个Activity一样,有自己的生命周期回调方法,您可以实现监控服务的状态变化,在适当的时间执行工作。如下面的框架所示演示了每个生命周期方法。

public class ExampleService extends Service {
int mStartMode;       // indicates how to behave if the service is killed
IBinder mBinder;      // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used

@Override
public void onCreate() {
// The service is being created
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}




 onStartCommand()
           系统调用这个方法当另一个组件,比如一个Activity,要求服务启动,通过调用由startService()。此方法执行后,Service启动,可以在后台运行下去。如果你实现这个,你必须自己在停止Service工作完成后,通过调用stopSelf()或stopService()。(特别提醒:如果你只是想提供绑定,您不需要实现此方法)。

onBind()

     系统调用该方法当另一个组件想绑定的Service(如执行RPC),通过调用bindService()。在你实现这种方法,您必须提供一个接口,客户使用与服务进行通信,通过返回一个IBinder。你必须实现这个方法,但是如果你不希望允许绑定,那么我们应该返回null。

onCreate()

    当系统第一次调用Service的时候,会调用这个方法,只调用那么一次。

 此外,跟Acitivity一样,Service需要声明在清单文件中,如下面所示

<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>


   接下来我还会详细的跟大家分享Service的具体使用案例,请各位敬请期待。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息