Androidサービス、ライフサイクルとか。

Androidはメモリが少なくなるとバックグラウンドになってるアプリを自動終了してしまうけれど、
じゃあサービスはどういう基準で終了されるのか、ということの確認。

サービスの起動方法は2種類。

  • startService(Intent)で起動する方法。stopServiceやstopself()を呼び出すことで停止。
  • bindService(Intent, ServiceConnection, int)を使う方法。UnbindServiceを呼び出すと停止。

上記2種類の起動方法によるライフサイクルはプロセスのライフサイクルを読むと次のように書いてある。

  • If the service is currently executing code in its onCreate(), onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.
  • If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible. Because only a few processes are generally visible to the user, this means that the service should not be killed except in extreme low memory conditions.
  • If there are clients bound to the service, then the service's hosting process is never less important than the most important client. That is, if one of its clients is visible to the user, then the service itself is considered to be visible.
  • A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

以下意訳:

  • onCreate(), onStartCommand() onDestroy()の実行中はフォアグラウンド扱い
  • サービス実行中は、visibleな(フォアな)プロセスより重要度は低いが、他のnot visibleなプロセスよりは重要度が高い(重要度が高い=killされにくい)
  • クライアントがサービスをバイドしているときは、一番重要度の高いクライアントよりも下の重要度にならない(同じかそれ以上の重要度)。クライアントがvisibleだったらサービスもvisibleと同じ扱い。
  • startForegroundで呼び出したときはプロセス自動killの対象にならない。(括弧の中には「フォアグラウンドのアプリがメモリを食ったらkillされることもあるが、考慮しなくていい」と書いてある)

さらに、プロセスにActivityなど別のコンポーネントがあって、そっちの重要度が高ければそれを優先する、らしい。

フォアなアプリで使う分には、よほどでなければkillされないようなのでひとまず安心。