Start a Service from an Activity

62,715

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

Use a Context.startService() method.

And read this.

Solution 5

The API Demos have some examples that launch services.

Share:
62,715
MAkS
Author by

MAkS

Updated on December 20, 2021

Comments

  • MAkS
    MAkS over 2 years

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