【移动开发】Service类onStartCommand()返回值和参数

Android开发的过程中,每次调用startService(Intent)的时候,都会调用该Service对象的onStartCommand(Intent,int,int)方法,然后在onStartCommand方法中做一些处理。然后我们注意到这个函数有一个int的返回值,这篇文章就是简单地讲讲int返回值的作用。

返回值
从Android官方文档中,知道onStartCommand有4种返回值:

START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。

START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。

START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。

START_STICKY_COMPATIBILITYSTART_STICKY的兼容版本,但不保证服务被kill后一定能重启。

http://developer.android.com/reference/android/app/Service.html

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Constant to return from {@link #onStartCommand}: compatibility 
  3.  * version of {@link #START_STICKY} that does not guarantee that 
  4.  * {@link #onStartCommand} will be called again after being killed. 
  5.  */  
  6. public static final int START_STICKY_COMPATIBILITY = 0;  
  7.   
  8. /** 
  9.  * Constant to return from {@link #onStartCommand}: if this service's 
  10.  * process is killed while it is started (after returning from 
  11.  * {@link #onStartCommand}), then leave it in the started state but 
  12.  * don't retain this delivered intent.  Later the system will try to 
  13.  * re-create the service.  Because it is in the started state, it will 
  14.  * guarantee to call {@link #onStartCommand} after creating the new 
  15.  * service instance; if there are not any pending start commands to be 
  16.  * delivered to the service, it will be called with a null intent 
  17.  * object, so you must take care to check for this. 
  18.  *  
  19.  * <p>This mode makes sense for things that will be explicitly started 
  20.  * and stopped to run for arbitrary periods of time, such as a service 
  21.  * performing background music playback. 
  22.  */  
  23. public static final int START_STICKY = 1;  
  24.   
  25. /** 
  26.  * Constant to return from {@link #onStartCommand}: if this service's 
  27.  * process is killed while it is started (after returning from 
  28.  * {@link #onStartCommand}), and there are no new start intents to 
  29.  * deliver to it, then take the service out of the started state and 
  30.  * don't recreate until a future explicit call to 
  31.  * {@link Context#startService Context.startService(Intent)}.  The 
  32.  * service will not receive a {@link #onStartCommand(Intent, int, int)} 
  33.  * call with a null Intent because it will not be re-started if there 
  34.  * are no pending Intents to deliver. 
  35.  *  
  36.  * <p>This mode makes sense for things that want to do some work as a 
  37.  * result of being started, but can be stopped when under memory pressure 
  38.  * and will explicit start themselves again later to do more work.  An 
  39.  * example of such a service would be one that polls for data from 
  40.  * a server: it could schedule an alarm to poll every N minutes by having 
  41.  * the alarm start its service.  When its {@link #onStartCommand} is 
  42.  * called from the alarm, it schedules a new alarm for N minutes later, 
  43.  * and spawns a thread to do its networking.  If its process is killed 
  44.  * while doing that check, the service will not be restarted until the 
  45.  * alarm goes off. 
  46.  */  
  47. public static final int START_NOT_STICKY = 2;  
  48.   
  49. /** 
  50.  * Constant to return from {@link #onStartCommand}: if this service's 
  51.  * process is killed while it is started (after returning from 
  52.  * {@link #onStartCommand}), then it will be scheduled for a restart 
  53.  * and the last delivered Intent re-delivered to it again via 
  54.  * {@link #onStartCommand}.  This Intent will remain scheduled for 
  55.  * redelivery until the service calls {@link #stopSelf(int)} with the 
  56.  * start ID provided to {@link #onStartCommand}.  The 
  57.  * service will not receive a {@link #onStartCommand(Intent, int, int)} 
  58.  * call with a null Intent because it will will only be re-started if 
  59.  * it is not finished processing all Intents sent to it (and any such 
  60.  * pending events will be delivered at the point of restart). 
  61.  */  
  62. public static final int START_REDELIVER_INTENT = 3;  

参数
onStartCommand()的函数原型,代码如下:
[java]  view plain copy
  1. /** 
  2.  * Called by the system every time a client explicitly starts the service by calling  
  3.  * {@link android.content.Context#startService}, providing the arguments it supplied and a  
  4.  * unique integer token representing the start request.  Do not call this method directly. 
  5.  *  
  6.  * <p>For backwards compatibility, the default implementation calls 
  7.  * {@link #onStart} and returns either {@link #START_STICKY} 
  8.  * or {@link #START_STICKY_COMPATIBILITY}. 
  9.  *  
  10.  * <p>If you need your application to run on platform versions prior to API 
  11.  * level 5, you can use the following model to handle the older {@link #onStart} 
  12.  * callback in that case.  The <code>handleCommand</code> method is implemented by 
  13.  * you as appropriate: 
  14.  *  
  15.  * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/ForegroundService.java 
  16.  *   start_compatibility} 
  17.  * 
  18.  * <p class="caution">Note that the system calls this on your 
  19.  * service's main thread.  A service's main thread is the same 
  20.  * thread where UI operations take place for Activities running in the 
  21.  * same process.  You should always avoid stalling the main 
  22.  * thread's event loop.  When doing long-running operations, 
  23.  * network calls, or heavy disk I/O, you should kick off a new 
  24.  * thread, or use {@link android.os.AsyncTask}.</p> 
  25.  * 
  26.  * @param intent The Intent supplied to {@link android.content.Context#startService},  
  27.  * as given.  This may be null if the service is being restarted after 
  28.  * its process has gone away, and it had previously returned anything 
  29.  * except {@link #START_STICKY_COMPATIBILITY}. 
  30.  * @param flags Additional data about this start request.  Currently either 
  31.  * 0, {@link #START_FLAG_REDELIVERY}, or {@link #START_FLAG_RETRY}. 
  32.  * @param startId A unique integer representing this specific request to  
  33.  * start.  Use with {@link #stopSelfResult(int)}. 
  34.  *  
  35.  * @return The return value indicates what semantics the system should 
  36.  * use for the service's current started state.  It may be one of the 
  37.  * constants associated with the {@link #START_CONTINUATION_MASK} bits. 
  38.  *  
  39.  * @see #stopSelfResult(int) 
  40.  */  
  41. public int onStartCommand(Intent intent, int flags, int startId) {  
  42.     onStart(intent, startId);  
  43.     return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;  
  44. }  
官方解释如下:
public int onStartCommand (Intent intent, int flags, int startId)
Added in  API level 5

Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly.

For backwards compatibility, the default implementation calls onStart(Intent, int) and returns either START_STICKY or START_STICKY_COMPATIBILITY.

If you need your application to run on platform versions prior to API level 5, you can use the following model to handle the older onStart(Intent, int)callback in that case. The handleCommand method is implemented by you as appropriate: 

[java]  view plain copy
  1. // This is the old onStart method that will be called on the pre-2.0  
  2. // platform.  On 2.0 or later we override onStartCommand() so this  
  3. // method will not be called.  
  4. @Override  
  5. public void onStart(Intent intent, int startId) {  
  6.     handleCommand(intent);  
  7. }  
  8.   
  9. @Override  
  10. public int onStartCommand(Intent intent, int flags, int startId) {  
  11.     handleCommand(intent);  
  12.     // We want this service to continue running until it is explicitly  
  13.     // stopped, so return sticky.  
  14.     return START_STICKY;  
  15. }  

Note that the system calls this on your service's main thread. A service's main thread is the same thread where UI operations take place for Activities running in the same process. You should always avoid stalling the main thread's event loop. When doing long-running operations, network calls, or heavy disk I/O, you should kick off a new thread, or use AsyncTask.

Parameters
intentThe Intent supplied to startService(Intent), as given. This may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.
flagsAdditional data about this start request. Currently either 0, START_FLAG_REDELIVERY, or START_FLAG_RETRY.
startIdA unique integer representing this specific request to start. Use with stopSelfResult(int).
Returns
  • The return value indicates what semantics the system should use for the service's current started state. It may be one of the constants associated with the START_CONTINUATION_MASK bits.
See Also


flags有3种取值,flags值和onStartCommand()的返回值有着直接的关系。如果Service被系统意外终止,重启的时候,传入的flags。官方文档描述:

public static final int START_FLAG_REDELIVERY
Added in  API level 5

This flag is set in onStartCommand(Intent, int, int) if the Intent is a re-delivery of a previously delivered intent, because the service had previously returned START_REDELIVER_INTENT but had been killed before calling stopSelf(int) for that Intent.

Constant Value: 1 (0x00000001)
public static final int START_FLAG_RETRY
Added in  API level 5

This flag is set in onStartCommand(Intent, int, int) if the Intent is a a retry because the original attempt never got to or returned fromonStartCommand(Intent, int, int).

Constant Value: 2 (0x00000002)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值