-- advertisement --

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