I am creating a music player application. I have created a MediaPlayerService
class and that has been working fine in MainActivity
. But I don't know how to pass that service without making it null and pass it to another activity, because I wanted to control it from another activity too. If I tried to get it from the main activity class then I got NullPointerException
.
Thanks in advance
Without code I can suggest one simple solution: Singleton pattern. In Kotlin you can define a singleton like this:
object MediaPlayerService {
fun play(...) {...}
}
and than use it:
MediaPlayerService.play(...)
This way you will have only one instance of the object. After creating the instance you can use Kotlin Flow for publish and subscribe. here you can read more about Kotlin Flows.