软件发布| 专题库| 优优资讯| 苹果专区| 安卓专区| 软件下载| 首页
优优资讯 电脑教程 安卓教程 安卓攻略 苹果教程 苹果攻略 新闻资讯

Android开发:Service本地服务

时间:2016-04-19 来源:本站整理 我要评论

欢迎来到优优下载站的编程开发专栏,今天为大家带来的是Android开发的Service本地服务文章,希望对您有帮助。除了这篇文章外,本站还有许多不同类型的文章供大家阅读,只要你输入关键字,再点击搜索。闲话不多说,一起来看看今天的内容吧!

Service是在一段不定的时间运行在后台,不和用户交互应用组件。每个Service必须在manifest中 通过来声明。可以通过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()会先加载 它。

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

生命周期

Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我 们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy() 方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行 onStart()方法。

而启动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交互的本地服务


  1. public class LocalService extends Service {
  2.  
  3. private static final String TAG = "LocalService";
  4.  
  5. @Override
  6. public IBinder onBind(Intent intent) {
  7. Log.i(TAG, "onBind");
  8. return null;
  9. }
  10.  
  11. @Override
  12. public void onCreate() {
  13. Log.i(TAG, "onCreate");
  14. super.onCreate();
  15. }
  16.  
  17. @Override
  18. public void onDestroy() {
  19. Log.i(TAG, "onDestroy");
  20. super.onDestroy();
  21. }
  22.  
  23. @Override
  24. public void onStart(Intent intent, int startId) {
  25. Log.i(TAG, "onStart");
  26. super.onStart(intent, startId);
  27. }
  28. }
  29.  
  30. Activity:
  31. public class ServiceActivity extends Activity {
  32.  
  33. @Override
  34. protected void onCreate(Bundle savedInstanceState) {
  35. super.onCreate(savedInstanceState);
  36. setContentView(R.layout.servicedemo);
  37.  
  38. ((Button) findViewById(R.id.startLocalService)).setOnClickListener(
  39. new View.OnClickListener(){
  40.  
  41. @Override
  42. public void onClick(View view) {
  43. // TODO Auto-generated method stub
  44. startService(new Intent("com.demo.SERVICE_DEMO"));
  45. }
  46. });
  47.  
  48. ((Button) findViewById(R.id.stopLocalService)).setOnClickListener(
  49. new View.OnClickListener(){
  50.  
  51. @Override
  52. public void onClick(View view) {
  53. // TODO Auto-generated method stub
  54. stopService(new Intent("com.demo.SERVICE_DEMO"));
  55. }
  56. });
  57. }
  58.  
  59. }

在AndroidManifest.xml添加:


  1. < service android:name =".LocalService" >
  2. < intent-filter >
  3. < action android:name ="com.demo.SERVICE_DEMO" />
  4. < category android:name ="android.intent.category.default" />
  5. intent-filter >
  6. 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. *

    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对象。


  1. /**
  2. *

    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.

     

  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" />
  2.  
  3. < activity android:name =".app.LocalServiceBinding" android:label ="@string/activity_local_service_binding" >
  4. < intent-filter >
  5. < action android:name ="android.intent.action.MAIN" />
  6. < category android:name ="android.intent.category.SAMPLE_CODE" />
  7. intent-filter >
  8. activity >

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

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

bindService:

1.LocalService : onCreate

2.LocalService : onBind

3.Activity: onServiceConnected

unbindService: 只是调用onDestroy

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

介绍onStartCommand()需要用到的几个常量 (引自官方文档)

START_NOT_STICKY

If the system kills the service after onStartCommand() returns, do notrecreate the service, unless there are pending intents to deliver. This is the safest option to avoid running your service when not necessary and when your application can simply restart any unfinished jobs.

START_STICKY

If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand(), but do not redeliver the last intent. Instead, the system calls onStartCommand() with a null intent, unless there were pending intents to start the service, in which case, those intents are delivered. This is suitable for media players (or similar services) that are not executing commands, but running indefinitely and waiting for a job.

START_REDELIVER_INTENT

If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand() with the last intent that was delivered to the service. Any pending intents are delivered in turn. This is suitable for services that are actively performing a job that should be immediately resumed, such as do wnloading a file.

Running a Service in the Foreground

具体内容查看官方文档,主要是使用 startForeground() 和 stopForeground()方法。

今天的文章到此结束,想要了解更多、更全面的编程开发技巧,请持续关注本站。除了文章外,本站还拥有着许多不同类型的优质手机软件,大家都可以进行免费下载安装,相信本站定会为大家带来完美的下载体验!【优优软件下载站】

用户评论

(已有0条评论)
表情
注:您的评论需要经过审核才能显示哦,请文明发言!
还没有评论,快来抢沙发吧!
快速检索
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z