• HOME
  • SERVICES
  • ABOUT
  • PLAYGROUND
  • BLOG
  • CONTACT

Run Android service in background

September 4, 2015No Commentsadmin

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

 

Tags: Android, coding, Developer, Java
Next post Programmatically read Android app version

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Optionally add ServletFilter in Spring
  • Returning NO CONTENT 204 from Spring Controller
  • Spring Java Config for Liquibase
  • Android – find contact Id by phone number
  • Ask built in Android contact viewer to show contact

Recent Comments

    Archives

    • February 2018
    • November 2015
    • September 2015

    Categories

    • Android
    • Coding
    • Developer
    • Java
    • Spring
    • Uncategorized

    Meta

    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.org
    © 2015 All rights reserved. EffCode AB