15

I want to implement the startForeground() method in the Service class for prevent service self kill.

Can anybody sent me code for implementing this method?

Amanda S
  • 3,266
  • 4
  • 33
  • 45
Jovan
  • 4,684
  • 13
  • 64
  • 98

4 Answers4

28

Jovan, here is a method for making compatible code for 2.0+ and 1.6- (the code shows you how to detect which one is compatible) http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html

For 2.0+, I put together some example code (using startForeground). Observe that some code is now deprecated, however, Notification.Builder uses API level 11 (3.x) which means I won't use that until most phones use a compatible Android version. Since the vast majority of phones is now running some version of 2.x, I think it's safe enough to skip the compatibility check.

final static int myID = 1234;

//The intent to launch when the user clicks the expanded notification
Intent intent = new Intent(this, SomeActivityToLaunch.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

//This constructor is deprecated. Use Notification.Builder instead
Notification notice = new Notification(R.drawable.icon_image, "Ticker text", System.currentTimeMillis());

//This method is deprecated. Use Notification.Builder instead.
notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);

notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);

put this code within onStartCommand() of your service and you're good to go. (But you could put this section of code anywhere in your service.)

P.S. to stop the service from being in foreground simply use stopForeground(true); anywhere in your service

Ahmad
  • 69,608
  • 17
  • 111
  • 137
Someone Somewhere
  • 23,475
  • 11
  • 118
  • 166
  • Why is it necessary to set FLAG_NO_CLEAR for a Service running on foreground? Is there a way to "clear" the notification of a foreground service? I know that AUTO_CANCEL [does not work](http://stackoverflow.com/questions/4561521/android-notification-flag-auto-cancel-not-working). – Eduardo Apr 02 '12 at 10:44
  • 1
    Why not use the notification builder compat provided in the support library to gain the advantages of the new API, keep compatibility, and not write deprecated code? – Abandoned Cart Aug 07 '13 at 17:01
  • @TwistedUmbrella: Android was (is) still evolving... at the time of writing the Android support library did not provide this capability. – Someone Somewhere Aug 20 '13 at 21:22
  • 2
    @SomeoneSomewhere Stopping by to make such a comment without updating the answer as well is poor practice. I have made the necessary changes and submitted a new answer for those who stumble across this topic. – Abandoned Cart Aug 23 '13 at 11:14
  • Hey, what does the ID do? – Ruchir Baronia Feb 06 '16 at 22:29
  • Ruchir Baronia- notifications need a non-zero ID – Saik Caskey May 23 '17 at 17:10
7

This code will use the best option available for any API by adding the Android support library to your project. In Eclipse, you would right click the project, go to Android Tools, and click the "Add Support Library..." option to download and add it.

final static int myID = 1234;

//The intent to launch when the user clicks the expanded notification
Intent intent = new Intent(this, SomeActivityToLaunch.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

if (Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.DONUT) {
// Build.VERSION.SDK_INT requires API 4 and would cause issues below API 4

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setTicker("TICKER").setContentTitle("TITLE").setContentText("CONTENT")
            .setWhen(System.currentTimeMillis()).setAutoCancel(false)
            .setOngoing(true).setPriority(Notification.PRIORITY_HIGH)
            .setContentIntent(pendIntent);
    Notification notification = builder.build();

} else {

    Notification notice = new Notification(R.drawable.icon_image, "Ticker text", System.currentTimeMillis());
    notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);

}
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notification);

Put the code in the start method you are using for your service, then when you want the foreground process to stop, call stopForeground(true); anywhere in your service

Abandoned Cart
  • 4,512
  • 1
  • 34
  • 41
  • 4
    You miss `builder.setSmallIcon(int)`. Without that custom builder will ignored with default notification. – Konstantin Konopko Feb 26 '14 at 09:19
  • The question wasn't about how to implement a custom notification. It was how to use the startForeground() method. What you do above and beyond that is your personal preference. – Abandoned Cart Mar 03 '14 at 04:07
1

http://developer.android.com/reference/android/app/Service.html#startForeground%28int,%20android.app.Notification%29

Falmarri
  • 47,727
  • 41
  • 151
  • 191
0

I'm not exactly sure if this is what you're looking for, but all you have to do is create a notification object (mOngoingNote below) and call startForeground using a notification ID along with the actual notification.

    startForeground(NOTEMAN_ID, mOngoingNote);
brack
  • 659
  • 7
  • 14