Some points 4. - Service

在Some points 1中对四大组件做了概览,这里详细记录一下官方文档上对Service做出的说明。

service运行在所在进程的主线程的,除了指定进程或线程,默认情况下既不会创建自己的线程也不会运行在另外的进程。因此如果 service 中执行了CPU敏感型的操作或其他阻塞线程的操作例如访问网络等,需要在 service 内另起线程来执行,否则会 ANR。

Service的类型

  • Scheduled - 在Android 5.0中新增的API JobSchedule中,service是被计划执行的,可以指定执行所需的网络环境和时间节点。
  • Started - Context.startService(),一旦启动服务可在后台无限期运行,即使启动服务的组件被销毁也不受影响。例:网络下载、上传文件。
  • Bound - Context.bindService(),绑定服务提供了一个客户端-服务器接口,允许组件与服务进行交互、发送请求、获取结果,甚至是利用进程间通信(IPC)跨进程执行这些操作。多个组件可以同时绑定该服务,但全部取消绑定后,该服务即被销毁。
    一个 service 可以同时是 started 和 bound 的。

Create a service

因为 service 是一个 Android 组件,因此也需要像 activity 一样在 manifest 中的 application 结点中声明。export=false属性可以防止其他应用启动本service。

Create a started service

当调用 Context.startService() ,就创建了started service,通过传递intent来指明服务的名称和携带数据,Service类中的onStartCommand()被回调,在这个方法中可以接收传递过来的intent。有两个类供继承来实现service:Service 和 IntentService。前者是所有service的基类,可以自行实现各种回调方法;后者是Service的一个子类,默认另启了一个工作线程来执行请求,如果不需要处理多重请求的话这是最佳的选择,只需实现onHandleIntent()来接收intent然后执行操作。

  • extends IntentService
    IntentService做了以下事情:

    • 创建了一个默认的工作线程来执行所有传递给onStartCommand()的intents,独立于应用的主线程。
    • 创建了一个工作队列,一次只向onHandleIntent()传递一个intent,无需担心多线程问题。
    • 在所有的服务请求都处理完毕后自动停止服务,无需再手动调用stopSelf()
    • 提供了onBind()返回null的默认实现。
    • 提供了onStartCommand()的默认实现,向工作队列发送intent,然后传至onHandleIntent()
  • extends Service
    而当有多线程需要,选择直接继承Service来实现的话,则需要手动实现一系列方法。Services文档中有一段代码示例演示了如何继承Service来实现,同时在service内开启了另外的线程来执行操作。

public class HelloService extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;

  // Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      @Override
      public void handleMessage(Message msg) {
          // Normally we would do some work here, like download a file.
          try {
              Thread.sleep(5000);
          } catch (InterruptedException e) {
              // Restore interrupt status.
              Thread.currentThread().interrupt();
          }
          stopSelf(msg.arg1);
      }
  }

  @Override
  public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);

      // If we get killed, after returning from here, restart
      return START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
      return null;
  }

  @Override
  public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
  }
}

值得注意的是在onStartCommand()中需要返回一个 int ,这个返回值描述了当系统杀死 service 后系统如何继续这个 service 。有以下3种值:

  • START_NOT_STICKY : 除非有新的intent传递过来,否则不重新创建service。
  • START_STICKY : 重新创建service,除非新传递过来 intent 否则以空 intent 调用onStartCommand() ,适用场景是Media player,service被系统杀死后立即重新创建,但是不执行任何命令,等待着用户的操作。
  • START_REDELIVER_INTENT: 立即重新生成service并且传入最后传递的intent,适用场景是需要立即恢复的操作,例如文件下载。

当 service 没有被 bound 的话,startService()是唯一的调用组件与 service 通信的入口,如果想返回结果用以交互,可以创建PendingIntent来发送广播,传递给service。

继承Service时需要stopService()来停止服务,当有多个请求连续回调onStartCommand()时,可以调用stopService(startId)来关闭,当此方法内的参数 startId 与 onStartCommand() 内的startId不一致时,不会关闭 service。

Create a bound service

当调用 Context.bindService() ,就创建了bound service。四大组件中只有Activity、Service 、Content Provider可以绑定服务,Broadcast receiver不可以绑定。应用场景为:应用中的组件想要通过service进行通信,以及向其他应用公开一些本应用的功能(IPC)。

要实现bound service,需要实现Service.onBind()方法来返回一个IBinder对象用以实现client与service的交互。调用 Context.bindService(Intent service,ServiceConnection,int flags)时需要提供一个 ServiceConnection 来监听 client 与 service 的连接, bindService() 是异步的,此方法会立即返回,且返回值是一个空值,但连接建立后,系统会回调 ServiceConnection 的 onServiceConnected() 方法,并且传回那个IBinder对象。多个client可以同时绑定同一个service,但是系统只会在第一个client绑定时回调service的onBind()方法,后续的其他client绑定时直接返回相同的IBinder对象而不再回调onBind()方法。

当最后一个 client 与 service 解绑时,service 会被系统销毁,除非同时也调用了Context.startService()使得服务同时也是一个started service,这时需要显式地调用stopService()stopService()来停止服务。

通常有3种方法来实现 IBinder:
(1) Extending the Binder class : 当服务为应用内的私有服务,或不涉及到应用内的跨进程通信时,使用这种方式来实现。client 接到在 service中定义的Binder对象来持有service的入口进而调用service内的方法。
(2) Using a Messenger : 当需要跨进程时,使用此方式。在service内new Messenger(Handler),Messenger.getBinder()可获得IBinder对象
用以进程间通信,使用 Handler & Message 实现service对于client发送过来的数据的处理,同时 client 也可以定义自己的Messenger,来处理service回传过来的数据。
这是实现IPC最简单的方式,因为 Messenger 将所有的请求排队到了单个线程中,因此无需设计service为线程安全的。
(3) Using AIDL : 全称为 Android Interface Definition Language ,将对象分解为原语,系统可以理解这些对象并在进程间编排它们以执行IPC。Messenger就是基于AIDL作为底层结构实现的,如果想要服务实现多线程需求可以AIDL实现,但一般来说这种需求很少见。

Context.bindService(Intent service,ServiceConnection,int flags)时需使用显式intent 来绑定服务,因为隐式intent 无法保证什么样的服务会被响应,存在安全隐患。在Android 5.0+使用隐式intent 来 bindService 会抛出异常。

Service 生命周期

LifeCircle : started service & bound service
Code about how to extend Binder :
public class LocalService extends Service {
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();
    // Random number generator
    private final Random mGenerator = new Random();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /** method for clients */
    public int getRandomNumber() {
      return mGenerator.nextInt(100);
    }
}
public class BindingActivity extends Activity {
    LocalService mService;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    /** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */
    public void onButtonClick(View v) {
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            int num = mService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
}

Code about how to use a Messenger :

public class MessengerService extends Service {
    /** Command to the service to display a message */
    static final int MSG_SAY_HELLO = 1;

    /**
     * Handler of incoming messages from clients.
     */
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SAY_HELLO:
                    Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    /**
     * Target we publish for clients to send messages to IncomingHandler.
     */
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    /**
     * When binding to the service, we return an interface to our messenger
     * for sending messages to the service.
     */
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
        return mMessenger.getBinder();
    }
}
public class ActivityMessenger extends Activity {
    /** Messenger for communicating with the service. */
    Messenger mService = null;

    /** Flag indicating whether we have called bind on the service. */
    boolean mBound;

    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the object we can use to
            // interact with the service.  We are communicating with the
            // service using a Messenger, so here we get a client-side
            // representation of that from the raw IBinder object.
            mService = new Messenger(service);
            mBound = true;
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
            mBound = false;
        }
    };

    public void sayHello(View v) {
        if (!mBound) return;
        // Create and send a message to the service, using a supported 'what' value
        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to the service
        bindService(new Intent(this, MessengerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • 上篇我们讲解了Android中的5中等级的进程,分别是:前台进程、可见进程、服务进程、后台进程、空进程。系统会按照...
    徐爱卿阅读 3,786评论 6 33
  • 服务基本上分为两种形式 启动 当应用组件(如 Activity)通过调用 startService() 启动服务时...
    pifoo阅读 1,201评论 0 8
  • 前言:本文所写的是博主的个人见解,如有错误或者不恰当之处,欢迎私信博主,加以改正!原文链接,demo链接 Serv...
    PassersHowe阅读 1,333评论 0 5
  • 大学的时候最喜欢参加各个社团的活动,总觉得可以遇见很多人,会发生很多故事。那时候除了上课什么都喜欢,贴吧,游戏,远...
    黑骑士_路西法_丸子阅读 191评论 0 0
  • 六便士是英国价值最低的银币,代表现实与卑微;而月亮则象征了崇高。两者都是圆形的,都闪闪发光,但本质却完全不同,或许...
    Derecho阅读 223评论 0 0