1# Mobly Android Device Service
2
3This tutorial shows how to use the service mechanism in Mobly's `AndroidDevice`
4controller.
5
6## Purpose
7Mobly's `AndroidDevice` controller is a Python module that lets users interact
8with Android devices with Python code.
9
10Often times, we need long-running services associated with `AndroidDevice`
11objects that persist during a test, e.g. adb logcat collection, screen
12recording. Meanwhile, we may want to alter the device's state during the
13test, e.g. reboot.
14
15`AndroidDevice` services makes it easier to implement long-running services.
16
17## Usage
18
19Implement your service per the
20[`BaseService` interface](https://github.com/google/mobly/blob/master/mobly/controllers/android_device_lib/services/base_service.py).
21
22Here is a dummy service example:
23
24`my_service.py`
25
26```python
27class Configs:
28  def __init__(self, secret=None):
29    self.secret = secret
30
31
32class MyService(base_service.BaseService):
33  """Dummy service demonstrating the service interface."""
34  def __init__(self, device, configs=None):
35    self._device = device
36    self._configs = configs
37    self._is_alive = False
38
39  def get_my_secret(self):
40    return self._configs.secret
41
42  @property
43  def is_alive(self):
44    """Override base class."""
45    return self._is_alive
46
47  def start(self):
48    """Override base class."""
49    self._is_alive = True
50
51  def stop(self):
52    """Override base class."""
53    self._is_alive = False
54```
55
56Once you have your service class, you can register your service with the
57`ServiceManager`. Let's say we already have an `AndroidDevice` instance `ad`:
58
59```python
60ad.services.register('secret_service',
61                     my_service.MyService,
62                     my_service.Configs(secret=42))
63```
64
65After registration, you can interact with the service instance:
66
67```python
68ad.services.secret_service.is_alive # True
69ad.services.secret_service.get_my_secret() # 42
70```
71
72When the `ad` reboots or gets destroyed, the service manager will handle the
73lifecycle changes of each service instance. So users don't have to explicitly
74write code to handle device state changes for each service, which makes the
75test verbose.
76
77The service interface also has optional methods `pause` and `resume` for
78services that are sensitive to device disconnect without reboot. For more
79details, see the docstrings of the
80[`BaseService` interface](https://github.com/google/mobly/blob/master/mobly/controllers/android_device_lib/services/base_service.py).
81