ほぼタイトルのままですが、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);
}
}