i am new to the jetpack compose. I did a lot of research on that topic but i can't find anything useful. What i wanna achieve is that if I close my window, my application will stay in the background and can be opened again from the tray. I managed to create the tray, but when i close the application window it closes the whole application. How can i achieve that?
This application will be on Windows and MacOS only. I don't care about android right now
CodePudding user response:
Edit: For version 0.4.0
I managed to figure it out. The main function should be an application, not the window
@OptIn(ExperimentalComposeUiApi::class)
fun main() = application {
}
And if the application contains both the Window and the Tray, it will continue to run in the background and does not close after the window is closed.
@OptIn(ExperimentalComposeUiApi::class)
fun main() = application {
Tray(
icon = BufferedImage(24, 24, 1),
menu = {
Item(
"Exit",
onClick = { exitProcess(1) }
)
}
)
Window{
Text("Hello World")
}
}
Edit: For version 1.0.0-beta5
Now you have to specify the onCloseRequest on the window object, if you leave it blank it won't close the window. In the application, create a variable which will indicate whether the window is open or not. Create the tray as before. The tray icon now requires a Painter object instead of a BufferedImage. Than simply check if the window open state is true, show the window, otherwise do nothing.
@OptIn(ExperimentalComposeUiApi::class)
fun main() = application {
val isOpen = remember { mutableStateOf(true)}
Tray(
icon = TrayIcon,
menu = {
Item(
"Exit",
onClick = { exitApplication() }
)
}
)
if(isOpen.value){
Window(
onCloseRequest = { isOpen.value = false }
) {
MaterialTheme {
Text("Hello World")
}
}
}
}
object TrayIcon : Painter() {
override val intrinsicSize = Size(256f, 256f)
override fun DrawScope.onDraw() {
drawOval(Color(0xFFFFA500))
}
}