Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Create a Background Service in Android

DZone's Guide to

How to Create a Background Service in Android

Not everything needs to run in a focussed application.

· Mobile Zone
Free Resource

To create a background service, first you need to add the service into your manifest file.  Then, create a class that extends service.  Finally, in your activity start the service.

1. First add the following service declaration in your application manifest file.

<service android:enabled="true" android:name=".MyService">
</service>

2. Create a new class MyService that extends Service class.

public class MyService extends Service {
  @Override
  public void onCreate() {
  }

  @Override
  public void onStart(Intent intent, int startId) {
    //do something
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
}

3. To start the service and stop the service:


public class MyActivity extends Activity {
  @Override
  public void onCreate() {
    …
    startService(new Intent(this, MyService.class);
  }

  @Override
  public void onStop() {
    …
    stopService(new Intent(this, MyService.class));
  }
}
Topics:
android

Published at DZone with permission of Nilanchala Panigrahy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}