Start a Service from an Activity

Viewed 64459

In my app, I have an Activity from which I want to start a Service. Can anybody help me?

7 Answers

The application can start the service with the help of the Context.startService method. The method will call the onCreate method of the service if service is not already created; else onStart method will be called. Here is the code:

Intent serviceIntent = new Intent();
serviceIntent.setAction("com.testApp.service.MY_SERVICE");
startService(serviceIntent);

The API Demos have some examples that launch services.

Use a Context.startService() method.

And read this.

in kotlin you can start service from activity as follow :

   startService!!.setOnClickListener { startService() }
 
   private fun startService(){
    startService(Intent(this, HitroService::class.java))
   }
Related