Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a Service from activity

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

like image 962
MAkS Avatar asked Feb 25 '10 15:02

MAkS


People also ask

How do I start a service from an activity?

A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. A service is bound when an application component binds to it by calling bindService().

How we can start activity and service in Android?

Start a service. An Android component (service, receiver, activity) can trigger the execution of a service via the startService(intent) method. // use this to start and trigger a service Intent i= new Intent(context, MyService. class); // potentially add data to the intent i.

Can we start a service without an activity?

It's not possible to have a Service on its own as a stand-alone "app". It needs to be started manually by a user through an Activity .

How do I start a service manifest?

Starting a service You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.


2 Answers

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.

like image 136
Vihaan Verma Avatar answered Sep 21 '22 12:09

Vihaan Verma


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); 
like image 23
Pierre-Antoine LaFayette Avatar answered Sep 21 '22 12:09

Pierre-Antoine LaFayette