Sometimes you want to have an Android service to run independent of the lifecycle of you Activities and application. This is convenient when you need to have background logic.
For example I’ve built an application that measures the usage of the phone. The app listens for screen events and updates a shared database. This could not be solved without an background service that runs continuously in background with an registered screen state receiver.
When starting an service in background you need to inform the user about that you app has something started and running. This is done by adding information to the Android notification bar – in this way the user is notified what apps are running.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class MyService extends Service { @Override publicvoid onCreate() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); // Tell which Activity to start when user clicks the item in the notification bar Intent resultIntent = new Intent(this, MyActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MyActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); // Configure text and icon to be shown in notification bar builder.setContentTitle("Hey"); builder.setContentText("This is a test of service in background"); builder.setSmallIcon(R.drawable.my_icon); // Create the notification Notification notification = builder.build(); // Starts the service in foreground with user defined service Id this.startForeground(123, notification); } public void stopMe() { // Stops the service and notification is removed from notification bar this.stopSelf(); } } |