FANDOM



Services run in the background, and cannot directly interact with the user.

They do not have a limited lifetime,  and can be started in response to the BOOT event is generated

Services are started through Intents

Services can use the notification system to interact with the user

Declare the Service in the Android ManifestEdit

<service android:name=".SimpleServiceService" />


Create a STICKY ServiceEdit

public class SimpleServiceService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
Log.v("SIMPLESERVICE","onCreate");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("SIMPLESERVICE","onStartCommand");
return START_STICKY;
}


Android Pre-version 2.0

//To support Adroind before version 2

@Override
public void onStart(Intent intent, int startid) {
Log.v("SIMPLESERVICE","onStart");
}

Clean up the service on shutdownEdit

public void onDestroy() {
Log.v("SIMPLESERVICE","onDestroy");
}

Control a service from an Activity screenEdit

public class SimpleServiceActivity extends Activity implements OnClickListener {

Button startServiceButton;
Button stopServiceButton;

Intent serviceIntent;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);


  startServiceButton = (Button) this.findViewById(R.id.StartServiceButton);
  stopServiceButton = (Button) this.findViewById(R.id.StopServiceButton);
  startServiceButton.setOnClickListener(this);
  stopServiceButton.setOnClickListener(this);

  serviceIntent = new Intent(this, SimpleServiceService.class);
}
public void onClick(View v) {
  if (v == startServiceButton) {

    startService(serviceIntent);
  }
  else if (v == stopServiceButton) {

    Context class.
    stopService(serviceIntent);

  }
}



Bind to a Service from an ActivityEdit

In order to have a button in an Activity interact with a Service, we have to bind to the Service like so;

if (v == startPlaybackButton) {

  startService(playbackServiceIntent);

  bindService(
    playbackServiceIntent,  
    serviceConnection,
    Context.BIND_AUTO_CREATE
  );

} else if (v == stopPlaybackButton) {

  unbindService(serviceConnection);
  stopService(playbackServiceIntent);

}

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.