Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreground service example [duplicate]

I am new to android. Can anyone post the link or code for "android foreground service example with notification". I googled , but didn't get any example of foreground service.

like image 338
user2533604 Avatar asked Feb 20 '14 17:02

user2533604


1 Answers

Create a Notification, perhaps using Notification.Builder or NotificationCompat.Builder, and pass that to startForeground() on the service:

public class Downloader extends IntentService {
  private static int FOREGROUND_ID=1338;

  public Downloader() {
    super("Downloader");
  }

  @Override
  public void onHandleIntent(Intent i) {
    startForeground(FOREGROUND_ID,
                    buildForegroundNotification(filename));

    // do useful work here

    stopForeground(true);
  }

  private Notification buildForegroundNotification(String filename) {
    NotificationCompat.Builder b=new NotificationCompat.Builder(this);

    b.setOngoing(true);

    b.setContentTitle(getString(R.string.downloading))
     .setContentText(filename)
     .setSmallIcon(android.R.drawable.stat_sys_download)
     .setTicker(getString(R.string.downloading));

    return(b.build());
  }
}

(a trimmed-down service from this sample project)

like image 138
CommonsWare Avatar answered Oct 02 '22 15:10

CommonsWare