Android/Service

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 Manifest


Create a STICKY Service
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 shutdown
public void onDestroy { Log.v("SIMPLESERVICE","onDestroy"); }

Control a service from an Activity screen
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 Activity
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); }