ContextExt.kt 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) Milan Jurkulák 2023.
  3. * Contact:
  4. * e: mimoccc@gmail.com
  5. * e: mj@mjdev.org
  6. * w: https://mjdev.org
  7. */
  8. package org.mjdev.tvlib.extensions
  9. import android.app.Activity
  10. import android.app.UiModeManager
  11. import android.content.Context
  12. import android.content.ContextWrapper
  13. import android.content.res.Configuration
  14. import android.os.Build
  15. import android.text.format.DateFormat
  16. import timber.log.Timber
  17. import java.util.Date
  18. @Suppress("unused", "UnusedReceiverParameter")
  19. object ContextExt {
  20. val Context.isEink: Boolean
  21. get() =
  22. Build.DEVICE == "Mudita Kompakt"
  23. val Context.isTV: Boolean
  24. get() = runCatching {
  25. val uiModeManager = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
  26. return uiModeManager.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION
  27. }.getOrNull() ?: false
  28. val Context.timeAsString: String
  29. get() = DateFormat.getTimeFormat(this).format(Date())
  30. val Context.dateAsString: String
  31. get() = DateFormat.getDateFormat(this).format(Date())
  32. inline fun <reified T : Activity> Context.activity(
  33. messageBlock: (context: Context) -> String = { ctx ->
  34. "Expected an activity context but instead found: $ctx"
  35. }
  36. ): T = let { context ->
  37. var ctx: Context? = context
  38. while (ctx != null && ctx is ContextWrapper) {
  39. if (ctx is T) {
  40. return@let ctx
  41. }
  42. ctx = try {
  43. ctx.baseContext
  44. } catch (e: Exception) {
  45. Timber.e(e)
  46. null
  47. }
  48. }
  49. throw IllegalStateException(messageBlock(this))
  50. }
  51. }