一、摘要
由于大多数被启动的services不需要同时处理多个请求,实际上是不安全的,最好的选择使用IntentService实现Service类,IntentService执行以下几个操作:
- 独立于UI thread创建一个默认的worker thread来处理所有发送到onStartCommand()的intents
- 创建一个worker queue在某个时间传递一个intent到onHandleIntent()实现方法,所以你不要担心多线程的问题
- 在所有启动的请求被处理后,停止服务,因此,你不用调用stopSelf()方法
- 默认情况下,onBind()实现方法返回null
- 默认情况下,onStartCommand()实现方法发送intent到work queue,然后传递到onHandleIntent()实现方法
二、必须重写的两个方法
所有的事实说明,你需要实现onHandleIntent()方法来处理客户端指定处理的工作,因此,需要重写父类的构造方法,代码如下:
- /**独立于UI线程创建一个worker thread来处理发送到onStartCommand()方法的intents
- * Created by Administrator on 2016/4/25.
- */
- public class SubIntentService extends android.app.IntentService {
- /**
- * 该构造方法是必须的,而且必须重写父类的IntentService(String)方法
- */
- public SubIntentService() {
- super("SubIntentService");
- }
- /**
- * The IntentService calls this method from the default worker thread with
- * the intent that started the service. When this method returns, IntentService
- * stops the service, as appropriate.
- */
- @Override
- protected void onHandleIntent(Intent intent) {
- }
- }
这个两个方法是必须:一、重写父类的构造方法super(String);二、重写onHandleIntent(Intent)。
三、重写额外的方法
如果想要重写其他的回调方法,比如:onCreate(),onStartCommand()或onDestroy(),必须保证回调super实现方法,以便IntentService()可以恰当处理work thread生命周期,代码如下:
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
- return super.onStartCommand(intent,flags,startId);
- }
除了onHandleIntent()不需要调用super实现方法外,onBind()是另外一个同样不需要调用super关键字的方法
你可能感兴趣的文章
来源:TeachCourse,
每周一次,深入学习Android教程,关注(QQ158#9359$239或公众号TeachCourse)
转载请注明出处: https://www.teachcourse.cn/1701.html ,谢谢支持!
转载请注明出处: https://www.teachcourse.cn/1701.html ,谢谢支持!
分类:Android Studio, Android基础
标签:Android, Android Studio