Start a Service from activity

Add this in your code

Intent serviceIntent = new Intent(this, ServiceName.class);
    startService(serviceIntent);

Dont forget to add service tag in AndroidManifest.xml file

<service android:name="com.example.ServiceName"></service>

From the Android official documentation:

Caution: A service runs in the same process as the application in which it is declared and in the main thread of that application, by default. So, if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.


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);

First create service from android Manifest.xml file (i.e from application tab) and give some name to it.
On the activity on some event like click or touch to include the code from the service:

public void onClick(View v)
{
    startService(new Intent(getApplicationContext(),Servicename.class));
}

If you want to stop the running or started service then include this code:

public void onclick(View v)
{
    stopService(new Intent(getApplicationContext,Servicename.class));
}