Проблема, с которой я сталкиваюсь, заключается в том, что первый когда я добавляю ComposeView, он работает отлично. Но когда я удаляю его и добавляю снова в WindowManager, композиция перестает работать. В результате анимация вообще отсутствует, а нажатия кнопок в ComposeView перестают работать.
Я пробовал управлять LifecycleOwner и экспериментировать с событиями жизненного цикла, но проблема не устранена.< /p>

Вот мой код:
Код: Выделить всё
class MyService2 : Service() {
override fun onBind(intent: Intent?): IBinder? {
TODO("Not yet implemented")
}
private val lifecycleOwner = MyLifecycleOwner()
companion object {
const val CHANNEL_ID = "ForegroundServiceChannel"
}
private val windowManager by lazy {
applicationContext.getSystemService(WINDOW_SERVICE) as WindowManager
}
private val layoutPrams by lazy {
WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
(WindowManager.LayoutParams.FLAG_FULLSCREEN
or WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE),
PixelFormat.TRANSLUCENT
)
}
override fun onCreate() {
super.onCreate()
lifecycleOwner.performRestore(null)
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
createNotificationChannel()
val notification = createNotification()
startForeground(579, notification)
}
private fun addComposeView() {
windowManager.addView(composeView, layoutPrams)
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
}
private val composeView: ComposeView by lazy {
ComposeView(this).apply {
val viewModelStore = ViewModelStore()
val viewModelStoreOwner = object : ViewModelStoreOwner{
override val viewModelStore: ViewModelStore
get() =viewModelStore
}
setViewTreeLifecycleOwner(lifecycleOwner)
setViewTreeSavedStateRegistryOwner(lifecycleOwner)
setViewTreeViewModelStoreOwner(viewModelStoreOwner)
setContent { ComposeView() }
}
}
@Preview
@Composable
fun ComposeView() {
Column(
modifier = Modifier
) {
Button(onClick = {
windowManager.removeView(composeView)
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
}) {
Text("Remove view")
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
intent?.let {
if (intent.getBooleanExtra("stop", false)) {
stopSelf()
} else if (intent.getBooleanExtra("add_compose", false)) {
addComposeView()
}
}
return START_STICKY
}
override fun onDestroy() {
super.onDestroy()
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
}
private fun createNotification(): Notification {
return NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("My Foreground Service")
.setContentText("Service is running in the foreground")
.setSmallIcon(R.drawable.ic_android_black_24dp) // replace with your icon
.build()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(serviceChannel)
}
}
}
private class MyLifecycleOwner : SavedStateRegistryOwner {
private var mLifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
private var mSavedStateRegistryController: SavedStateRegistryController = SavedStateRegistryController.create(this)
override val lifecycle: Lifecycle
get() = mLifecycleRegistry
override val savedStateRegistry: SavedStateRegistry
get() = mSavedStateRegistryController.savedStateRegistry
val isInitialized: Boolean
get() = true
fun setCurrentState(state: Lifecycle.State) {
mLifecycleRegistry.currentState = state
}
fun handleLifecycleEvent(event: Lifecycle.Event) {
mLifecycleRegistry.handleLifecycleEvent(event)
}
fun performRestore(savedState: Bundle?) {
mSavedStateRegistryController.performRestore(savedState)
}
fun performSave(outBundle: Bundle) {
mSavedStateRegistryController.performSave(outBundle)
}
}
[*]Настройка событий lifecycleOwner (
Код: Выделить всё
ON_CREATE
[*]Проверка того, что ComposeView создается только один раз и используется повторно.
< /ul>
Что может быть причиной того, что композиция перестает работать после повторного добавления представления в WindowManager? Есть ли конкретные события или стратегии жизненного цикла, которыми мне нужно лучше управлять?
Подробнее здесь: https://stackoverflow.com/questions/791 ... dowmanager