前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android service原理及免杀(2)

android service原理及免杀(2)

作者头像
随心助手
发布2019-12-05 18:10:51
4030
发布2019-12-05 18:10:51
举报
文章被收录于专栏:nginx遇上redisnginx遇上redis

二. 实现Service

实现服务有两种方式,继承service或者IntentService。后者是前者的子类。前者包含上一章节中Service的几个重要的方法,用于普通的服务。后者可以自己开一个工作线程,串行的处理多个请求。

2.1继承Service

继承Service就可以实现对请求多线程的处理,前面介绍了Service的生命周期,可以按照生命周期实现方法,就不放示例了。

2.2继承IntentService

大多数服务不需要同时处理多个请求,继承IntentService是最好的选择。

IntentService处理流程:

1.创建按默认的一个worker线程处理传递给onStartCommand()所有的intent,在非UI线程中工作。

2.创建一个工作队列依次传递一个intent到你实现的onHandleIntent()方法,避免了多线程。

3.在所有启动请求被处理后自动关闭服务,不需要调用stopSelf()

4.默认提供onBind()的实现,并返回null

5.默认提供onStartCommand()的实现,实现发送intent到工作队列再到你的onHandleIntent()方法实现。

这些都加入到IntentService中了,你需要做的就是实现构造方法和onHandleIntent(),如下:

代码语言:javascript
复制
public class HelloIntentService extends IntentService {
 
  /**
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }
 
  /**
   * 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) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 nginx遇上redis 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档