Service运行在宿主进程的的主线程中——Service不会创建它自己的进程,也不会运行在分开的进程中(除非你特别指定)。这意味着,如果你的Service要做任何占用CPU或者阻塞操作(例如播放音乐或者网络操作),你应该单独为Service创建一个线程。通过使用单独的线程,你会减小应用程序未响应(ANR-Application Not Responding)错误,并且让应用程序主线程保持用户与Activity进行交互。
importandroid.app.Service;importandroid.content.Intent;importandroid.os.IBinder;publicclassExampleServiceextendsService{intmStartMode;// indicates how to behave if the service is killedIBindermBinder;// interface for clients that bindbooleanmAllowRebind;// indicates whether onRebind should be used@OverridepublicvoidonCreate(){// The service is being created}@OverridepublicintonStartCommand(Intentintent,intflags,intstartId){// The service is starting, due to a call to startService()returnmStartMode;}@OverridepublicIBinderonBind(Intentintent){// A client is binding to the service with bindService()returnmBinder;}@OverridepublicbooleanonUnbind(Intentintent){// All clients have unbound with unbindService()returnmAllowRebind;}@OverridepublicvoidonRebind(Intentintent){// A client is binding to the service with bindService(),// after onUnbind() has already been called}@OverridepublicvoidonDestroy(){// The service is no longer used and is being destroyed}}