How to call stopservice() method of Service class from the calling activity class

后端 未结 5 851
北海茫月
北海茫月 2020-11-30 06:19

I am trying to call my service class\'s stopService() method from my activity. But I dont know how to access stopservice method from my activity class. I have the below code

5条回答
  •  死守一世寂寞
    2020-11-30 07:03

    In Kotlin you can do this...

    Service:

    class MyService : Service() {
        init {
            instance = this
        }
    
        companion object {
            lateinit var instance: MyService
    
            fun terminateService() {
                instance.stopSelf()
            }
        }
    }
    

    In your activity (or anywhere in your app for that matter):

    btn_terminate_service.setOnClickListener {
        MyService.terminateService()
    }
    

    Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.

提交回复
热议问题