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

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

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

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}