【安卓篇】Service类的onStartCommand与onStart方法介绍

来源:互联网 发布:网络棋牌机器人规律 编辑:程序博客网 时间:2024/06/06 00:33

  初次接触android,在学习service过程中,创建一个类继承至Service类之后,复写方法时,发现复写onStar()方法后,eclipse提示该方法过时,于是,打开android的api文档,发现Service介绍中有如下一句话

  If you're building an application for Android 1.6 or lower, you need to implementonStart(), instead of onStartCommand() (in Android 2.0, onStart() was deprecated in favor of onStartCommand()).

      看到这里才恍然大悟,原来onStart方法是在Android2.0之前的平台使用的.在2.0及其之后,则需重写onStartCommand方法,同时,旧的onStart方法则不会再被直接调用。继续查询android的api文档,文档中有如下话语:

  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:

// 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;}
  文档中的介绍可以看出,如果我们的android平台在level 5版本之前,我们可以回调事例中的onStart(),而通过事例中给出的方法中可以看出。onStart方法中调用了handleCommand(intent)方法,在onStartCommand方法中,同样调用了handleCommand(intent)方法,这也就意味着,onStartCommand方法里调用 了onStart。这便实现了android应用的向前兼容。
  通过上面文档给出的事例可以看出,onStartCommand较之onStart方法,最大的不同是返回了一个
START_STICKY常量。

  查看onStartCommand方法的API,有以下信息

Parameters
  intent:The 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.

  flags:Additional data about this start request. Currently either 0, START_FLAG_REDELIVERY, or START_FLAG_RETRY.

    startId:A 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.

  【参考文档】http://tool.oschina.net/apidocs/apidoc?api=android/reference

  Android中Service类onStartCommand:http://blog.csdn.net/lizzy115/article/details/7001731

0 0
原创粉丝点击