Service api

来源:互联网 发布:咸阳软件培训学校 编辑:程序博客网 时间:2024/06/08 06:45

public int onStartCommand (Intent intent, int flags, int startId)

Added in API level 5

调用startService(Intent)启动service的时候,onStartCommand会被系统回调。回调参数Intent为startService(Intent)中的参数,和一个用来表示这次请求的整数token。不要直接调用次方法。

为了向后兼容,默认实现了onStart(Intent,int)并且返回 START_STICKY or START_STICKY_COMPATIBILITY.

如果你的应用是运行在level 5 之前的,你可以仿照下面的处理方法。onStartCommand(Intent intent, int flags, int startId)方法在level 5后面的系统中被调用。

// This is the old onStart method that will be called on the pre-2.0// platform.  On 2.0 or later we override onStartCommand() so this// method will not be called.@Overridepublic void onStart(Intent intent, int startId) {    handleCommand(intent);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    handleCommand(intent);    // We want this service to continue running until it is explicitly    // stopped, so return sticky.    return START_STICKY;}

注意:上面的方法是在service的主线程中被调用的。service的主线程为ui线程。你应该避免主线程的事件循环被阻塞.当处理长时间的操作,网络交互,或大量磁盘io的操作的时候,应该用一个新的线程,或使用AsyncTask;

Parameters
 intent  与提供给startService(Intent)中的intent相同。如果service所在的进程被销毁,并且该方法之前返回的不是START_STICKY_COMPATIBILITY重新被启动intent可能为空。 flags  start 请求的附加数据。可能是0, START_FLAG_REDELIVERY, or START_FLAG_RETRY. startId 代表这次请求的数字标识。在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.
  • 返回值表明系统如何处理当前启动的service的启动状态。返回值可能与START_CONTINUATION_MASK位相关的常量。
See Also
  • stopSelfResult(int)