サービスは、時間のかかる処理を画面の状態から独立して行うための仕組みです。アクティビティはライフサイクルの変化によりシステムによって終了させられてしまうことがありますが、サービスとして実行していれば処理を続行できます。
サービスを開始する方法は、
の2つがあります。
Context.startService()
Context.bindService()
getSystemService()メソッドでサービスを取得できます。
public Object getSystemService (String name)getSystemService - Activity | Android Developers
取得するサービスはnameで指定し、それは下表のように定義されています。
| 定数 | 取得の対象 | 説明 |
|---|---|---|
| ACCESSIBILITY_SERVICE | AccessibilityManager | giving the user feedback for UI events through the registered event listeners. |
| ACCOUNT_SERVICE | AccountManager | receiving intents at a time of your choosing. |
| ACTIVITY_SERVICE | ActivityManager | interacting with the global system state. |
| ALARM_SERVICE | AlarmManager | receiving intents at a time of your choosing. |
| AUDIO_SERVICE | AudioManager | handling management of volume, ringer modes and audio routing. |
| CLIPBOARD_SERVICE | ClipboardManager | accessing and modifying the contents of the global clipboard. |
| CONNECTIVITY_SERVICE | ConnectivityManager | handling management of network connections. |
| DEVICE_POLICY_SERVICE | DevicePolicyManager | working with global device policy management. |
| DOWNLOAD_SERVICE | DownloadManager | requesting HTTP downloads. |
| DROPBOX_SERVICE | DropBoxManager | recording diagnostic logs. |
| INPUT_METHOD_SERVICE | InputMethodManager | accessing input methods. |
| KEYGUARD_SERVICE | NotificationManager | controlling keyguard. |
| LAYOUT_INFLATER_SERVICE | LayoutInflater | inflating layout resources in this context. |
| LOCATION_SERVICE | LocationManager | controlling location updates. |
| NFC_SERVICE | NfcManager | using NFC. |
| NOTIFICATION_SERVICE | NotificationManager | informing the user of background events. |
| POWER_SERVICE | PowerManager | controlling power management, including "wake locks," which let you keep the device on while you're running long tasks. |
| SEARCH_SERVICE | SearchManager | handling searches. |
| SENSOR_SERVICE | SensorManager | accessing sensors. |
| STORAGE_SERVICE | StorageManager | accessing system storage functions. |
| TELEPHONY_SERVICE | TelephonyManager | handling management the telephony features of the device. |
| UI_MODE_SERVICE | UiModeManager | controlling UI modes. |
| USB_SERVICE | UsbManager | access to USB devices (as a USB host) and for controlling this device's behavior as a USB device. |
| VIBRATOR_SERVICE | Vibrator | interacting with the vibration hardware. |
| WALLPAPER_SERVICE | WallpaperService | accessing wallpapers. |
| WIFI_SERVICE | WifiManager | handling management of Wi-Fi access. |
| WINDOW_SERVICE | WindowManager | accessing the system's window manager. |
コールバックを利用することで、サービスで発生したイベントをアクティビティに通知できます。
public IntentService (String name)IntentService - IntentService | Android Developers
nameはワーカースレッドの名前となります。これはデバッグ時のみ意味を持ちます。