LoginSignup
4
3

More than 3 years have passed since last update.

OSバージョンを意識せずServiceをフォアグラウンド実行する方法

Last updated at Posted at 2019-06-11

ほぼタイトルのままですが、Serviceをフォアグラウンド実行する際に、OSバージョンを意識せず実装する方法です。

何てことはないのですが、ContextCompatクラスにstartForegroundService(context, intent)というメソッドがあるので、それを使うだけです。
ContextCompat#startForegroundService(context, intent)

処理としては、OSバージョンによってcontext.startForegroundService(intent)context.startService(intent)を呼び分けています。

ContextCompat.java
/**
 * startForegroundService() was introduced in O, just call startService
 * for before O.
 *
 * @param context Context to start Service from.
 * @param intent The description of the Service to start.
 *
 * @see Context#startForegroundService(Intent)
 * @see Context#startService(Intent)
 */
public static void startForegroundService(@NonNull Context context, @NonNull Intent intent) {
    if (Build.VERSION.SDK_INT >= 26) {
        context.startForegroundService(intent);
    } else {
        // Pre-O behavior.
        context.startService(intent);
    }
}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3