`
eric_hwp
  • 浏览: 119747 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

android学习笔记(二)四大组件Service详解

 
阅读更多

service可以在和多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等,总之服务嘛,总是藏在后头的。

  Service是在一段不定的时间运行在后台,不和用户交互应用组件。每个Service必须在manifest中 通过<service>来声明。可以通过contect.startservice和contect.bindserverice来启动。

  Service和其他的应用组件一样,运行在进程的主线程中。这就是说如果service需要很多耗时或者阻塞的操作,需要在其子线程中实现。

  service的两种模式(startService()/bindService()不是完全分离的):

  本地服务 Local Service 用于应用程序内部。

  它可以启动并运行,直至有人停止了它或它自己停止。在这种方式下,它以调用Context.startService()启动,而以调用Context.stopService()结束。它可以调用Service.stopSelf() 或 Service.stopSelfResult()来自己停止。不论调用了多少次startService()方法,你只需要调用一次stopService()来停止服务。

  用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行,这样用户体验比较好。
  远程服务 Remote Service 用于android系统内部的应用程序之间。

  它可以通过自己定义并暴露出来的接口进行程序操作。客户端建立一个到服务对象的连接,并通过那个连接来调用服务。连接以调用Context.bindService()方法建立,以调用 Context.unbindService()关闭。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService()会先加载它。

  可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。

 

 生命周期

使用context.startService() 启动Service是会会经历:

  context.startService() ->onCreate()- >onStart()->Service running

  context.stopService() | ->onDestroy() ->Service stop

  如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。

  stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service。

  所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy
  使用使用context.bindService()启动Service会经历:

  context.bindService()->onCreate()->onBind()->Service running

  onUnbind() -> onDestroy() ->Service stop

  onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind->onDestroy相应退出。

  所以调用bindService的生命周期为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。

  在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。


而启动service,根据onStartCommand的返回值不同,有两个附加的模式:

  1. START_STICKY 用于显示启动和停止service。

  2. START_NOT_STICKY或START_REDELIVER_INTENT用于有命令需要处理时才运行的模式。

  服务不能自己运行,需要通过调用Context.startService()或Context.bindService()方法启动服务。这两个方法都可以启动Service,但是它们的使用场合有所不同。

  1. 使用startService()方法启用服务,调用者与服务之间没有关连,即使调用者退出了,服务仍然运行。

  如果打算采用Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。

  如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。

  采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。

  2. 使用bindService()方法启用服务,调用者与服务绑定在了一起,调用者一旦退出,服务也就终止,大有“不求同时生,必须同时死”的特点。

  onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()方法并不会导致该方法被多次调用。

  采用Context.bindService()方法启动服务时只能调用onUnbind()方法解除调用者与服务解除,服务结束时会调用onDestroy()方法。

  看看官方给出的比较流程示意图:

  官方文档告诉我们,一个service可以同时start并且bind,在这样的情况,系统会一直保持service的运行状态如果service已经start了或者BIND_AUTO_CREATE标志被设置。如果没有一个条件满足,那么系统将会调用onDestory方法来终止service.所有的清理工作(终止线程,反注册接收器)都在onDestory中完成。

  拥有service的进程具有较高的优先级

  官方文档告诉我们,Android系统会尽量保持拥有service的进程运行,只要在该service已经被启动(start)或者客户端连接(bindService)到它。当内存不足时,需要保持,拥有service的进程具有较高的优先级。

  1. 如果service正在调用onCreate,onStartCommand或者onDestory方法,那么用于当前service的进程则变为前台进程以避免被killed。

  2. 如果当前service已经被启动(start),拥有它的进程则比那些用户可见的进程优先级低一些,但是比那些不可见的进程更重要,这就意味着service一般不会被killed.

  3. 如果客户端已经连接到service (bindService),那么拥有Service的进程则拥有最高的优先级,可以认为service是可见的。

  4. 如果service可以使用startForeground(int, Notification)方法来将service设置为前台状态,那么系统就认为是对用户可见的,并不会在内存不足时killed。

  如果有其他的应用组件作为Service,Activity等运行在相同的进程中,那么将会增加该进程的重要性。

  本地service

  1.不需和Activity交互的本地服务

public class LocalService extends Service {

 

private static final String TAG = "LocalService";

 

@Override

public IBinder onBind(Intent intent) {

   Log.i(TAG, "onBind");

  return null;

}

 

   @Override

   public void onCreate() {

      Log.i(TAG, "onCreate");

     super.onCreate();

}

 

@Override

public void onDestroy() {

Log.i(TAG, "onDestroy");

super.onDestroy();

}

 

@Override

public void onStart(Intent intent, int startId) {

Log.i(TAG, "onStart");

super.onStart(intent, startId);

}

}

 

  Activity:

public class ServiceActivity extends Activity {

 

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.servicedemo);

 

((Button) findViewById(R.id.startLocalService)).setOnClickListener(

new View.OnClickListener(){

 

@Override

public void onClick(View view) {

// TODO Auto-generated method stub

startService(new Intent("com.demo.SERVICE_DEMO"));


});

 

((Button) findViewById(R.id.stopLocalService)).setOnClickListener(

new View.OnClickListener(){

 

@Override

public void onClick(View view) {

// TODO Auto-generated method stub

stopService(new Intent("com.demo.SERVICE_DEMO"));

}

});

}

 

}

 

复制代码

 

 

  在AndroidManifest.xml添加:

<service android:name=".LocalService">

<intent-filter>

<action android:name="com.demo.SERVICE_DEMO" />

<category android:name="android.intent.category.default" />

</intent-filter>

</service>

复制代码

  否则启动服务时会提示new Intent找不到"com.demo.SERVICE_DEMO"。

  对于这类不需和Activity交互的本地服务,是使用startService/stopService的最好例子。

  运行时可以发现第一次startService时,会调用onCreate和onStart,在没有stopService前,无论点击多少次startService,都只会调用onStart。而stopService时调用onDestroy。再次点击stopService,会发现不会进入service的生命周期的,即不会再调用onCreate,onStart和onDestroy。

  而onBind在startService/stopService中没有调用。

  2.本地服务和Activity交互

  对于这种case,官方的sample(APIDemo\app.LocalService)是最好的例子:

  1. /**
  2. * This is an example of implementing an application service that runs locally
  3. * in the same process as the application. The {@link LocalServiceController}
  4. * and {@link LocalServiceBinding} classes show how to interact with the
  5. * service.
  6. *
  7. * <p>Notice the use of the {@link NotificationManager} when interesting things
  8. * happen in the service. This is generally how background services should
  9. * interact with the user, rather than doing something more disruptive such as
  10. * calling startActivity().
  11. */
  12. public class LocalService extends Service {
  13. private NotificationManager mNM;
  14.  
  15. /**
  16. * Class for clients to access. Because we know this service always
  17. * runs in the same process as its clients, we don't need to deal with
  18. * IPC.
  19. */
  20. public class LocalBinder extends Binder {
  21. LocalService getService() {
  22. return LocalService.this;
  23. }
  24. }
  25.  
  26. @Override
  27. public void onCreate() {
  28. mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  29.  
  30. // Display a notification about us starting. We put an icon in the status bar.
  31. showNotification();
  32. }
  33.  
  34. @Override
  35. public int onStartCommand(Intent intent, int flags, int startId) {
  36. Log.i("LocalService", "Received start id " + startId + ": " + intent);
  37. // We want this service to continue running until it is explicitly
  38. // stopped, so return sticky.
  39. return START_STICKY;
  40. }
  41.  
  42. @Override
  43. public void onDestroy() {
  44. // Cancel the persistent notification.
  45. mNM.cancel(R.string.local_service_started);
  46.  
  47. // Tell the user we stopped.
  48. Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
  49. }
  50.  
  51. @Override
  52. public IBinder onBind(Intent intent) {
  53. return mBinder;
  54. }
  55.  
  56. // This is the object that receives interactions from clients. See
  57. // RemoteService for a more complete example.
  58. private final IBinder mBinder = new LocalBinder();
  59.  
  60. /**
  61. * Show a notification while this service is running.
  62. */
  63. private void showNotification() {
  64. // In this sample, we'll use the same text for the ticker and the expanded notification
  65. CharSequence text = getText(R.string.local_service_started);
  66.  
  67. // Set the icon, scrolling text and timestamp
  68. Notification notification = new Notification(R.drawable.stat_sample, text,
  69. System.currentTimeMillis());
  70.  
  71. // The PendingIntent to launch our activity if the user selects this notification
  72. PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
  73. new Intent(this, LocalServiceController.class), 0);
  74.  
  75. // Set the info for the views that show in the notification panel.
  76. notification.setLatestEventInfo(this, getText(R.string.local_service_label),
  77. text, contentIntent);
  78.  
  79. // Send the notification.
  80. // We use a layout id because it is a unique number. We use it later to cancel.
  81. mNM.notify(R.string.local_service_started, notification);
  82. }
  83. }
复制代码

  这里可以发现onBind需要返回一个IBinder对象。也就是说和上一例子LocalService不同的是,

  1. 添加了一个public内部类继承Binder,并添加getService方法来返回当前的Service对象;

  2. 新建一个IBinder对象--new那个Binder内部类;

  3. onBind方法返还那个IBinder对象。

  Activity:

  1. /**
  2. * <p>Example of binding and unbinding to the {@link LocalService}.
  3. * This demonstrates the implementation of a service which the client will
  4. * bind to, receiving an object through which it can communicate with the service.</p>
  5. */
  6. public class LocalServiceBinding extends Activity {
  7. private boolean mIsBound;
  8. private LocalService mBoundService;
  9.  
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13.  
  14. setContentView(R.layout.local_service_binding);
  15.  
  16. // Watch for button clicks.
  17. Button button = (Button)findViewById(R.id.bind);
  18. button.setOnClickListener(mBindListener);
  19. button = (Button)findViewById(R.id.unbind);
  20. button.setOnClickListener(mUnbindListener);
  21. }
  22.  
  23. private ServiceConnection mConnection = new ServiceConnection() {
  24. public void onServiceConnected(ComponentName className, IBinder service) {
  25. // This is called when the connection with the service has been
  26. // established, giving us the service object we can use to
  27. // interact with the service. Because we have bound to a explicit
  28. // service that we know is running in our own process, we can
  29. // cast its IBinder to a concrete class and directly access it.
  30. mBoundService = ((LocalService.LocalBinder)service).getService(); 
  31.  
  32. // Tell the user about this for our demo.
  33. Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
  34. Toast.LENGTH_SHORT).show();
  35. }
  36.  
  37. public void onServiceDisconnected(ComponentName className) { 
  38. // This is called when the connection with the service has been
  39. // unexpectedly disconnected -- that is, its process crashed.
  40. // Because it is running in our same process, we should never
  41. // see this happen.
  42. mBoundService = null;
  43. Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,
  44. Toast.LENGTH_SHORT).show();
  45. }
  46. };
  47.  
  48. private OnClickListener mBindListener = new OnClickListener() {
  49. public void onClick(View v) {
  50. // Establish a connection with the service. We use an explicit
  51. // class name because we want a specific service implementation that
  52. // we know will be running in our own process (and thus won't be
  53. // supporting component replacement by other applications).
  54. bindService(new Intent(LocalServiceBinding.this, 
  55. LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
  56. mIsBound = true;
  57. }
  58. };
  59.  
  60. private OnClickListener mUnbindListener = new OnClickListener() {
  61. public void onClick(View v) {
  62. if (mIsBound) {
  63. // Detach our existing connection.
  64. unbindService(mConnection);
  65. mIsBound = false;
  66. }
  67. }
  68. };
  69. }
复制代码



  明显看出这里面添加了一个名为ServiceConnection类,并实现了onServiceConnected(从IBinder获取Service对象)和onServiceDisconnected(set Service to null)。

  而bindService和unbindService方法都是操作这个ServiceConnection对象的。

  AndroidManifest.xml里添加:

  1.   <service android:name=".app.LocalService" />
复制代码

  这里没什么特别的,因为service没有需要什么特别的action,所以只是声明service而已,而activity和普通的没差别。

  运行时,发现调用次序是这样的:

  bindService:

  1.LocalService : onCreate

  2.LocalService : onBind

  3.Activity: onServiceConnected

  unbindService: 只是调用onDestroy

  可见,onStart是不会被调用的,而onServiceDisconnected没有调用的原因在上面代码的注释有说明。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics