Closed5

【雑記】lifecycle2.6以降で、ComposeをServiceで使う際の備忘録

pecopeco

問題点

APIに変更があった
2年近く前の記事なので致し方なし

pecopeco

一部抜粋
詳細はドキュメントを見てください

Lifecycle 2.5 Lifecycle 2.5 (KTX) Lifecycle 2.6
ViewTreeLifecycleOwner.set(view, owner) ViewTreeLifecycleOwner.set(view, owner) view.setViewTreeLifecycleOwner(owner)
Savedstate 2.0 Savedstate 2.1
ViewTreeSavedStateRegistryOwner.set(view, owner) view.setViewTreeSavedStateRegistryOwner(owner)
pecopeco

対応後のコード

APIが変わってるだけで内容は同じです
一つ一つ対応してそれぞれ元記事と同じエラーが起きました
とりあえずは動きました

class AppService: LifecycleService(), SavedStateRegistryOwner  {

    private val savedStateRegistryController = SavedStateRegistryController.create(this)

    override val savedStateRegistry: SavedStateRegistry
        get() = savedStateRegistryController.savedStateRegistry

    private val params by lazy {
        WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )
    }

    private val windowManager by lazy {
        getSystemService(Context.WINDOW_SERVICE) as WindowManager
    }

    private val composeView by lazy {
        ComposeView(this).apply {
            setContent {
                Text("Hello Compose")
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        composeView.setViewTreeLifecycleOwner(this)
        composeView.setViewTreeSavedStateRegistryOwner(this)
        savedStateRegistryController.performRestore(null)
        windowManager.addView(composeView, params)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        return START_NOT_STICKY
    }

    override fun onDestroy() {
        windowManager.removeView(composeView)
        super.onDestroy()
    }
}
このスクラップは4ヶ月前にクローズされました