Question

I'm having a problem with my IntentService. Every time I start my service, the onDestroy() method is called as soon as the service becomes idle. I set up my service to run in the foreground, and despite this the service is still being killed right away. I have only one other activity in my application, and it is not calling stopService().

Reading the developer docs gives me the impression that calling startForeground() will allow your service to persist, even when idle, except when there is an very high demand for memory, or am I reading this wrong?

My code below:

public class FileMonitorService extends IntentService {
  public int mNotifyId = 273;
  public FileMonitorService(){
    super("FileMonitorService");
}

@Override
protected void onHandleIntent(Intent arg0) {

}

@Override
public void onDestroy() {       
    Toast.makeText(this, getText(R.string.toast_service_stop), Toast.LENGTH_SHORT).show();
    stopForeground(true);
    super.onDestroy();      
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {      
    Notification notification = new Notification(R.drawable.icon, getText(R.string.notification_short), System.currentTimeMillis());
    notification.flags|=Notification.FLAG_NO_CLEAR;     
    Intent notificationIntent = new Intent(this, FileMonitorActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, getText(R.string.notification_short),getText(R.string.notification_long), pendingIntent);
    startForeground(mNotifyId, notification);


    Toast.makeText(this, getText(R.string.toast_service_start), Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent, flags, startId);
}   
  }
Was it helpful?

Solution

You need to look into using a regular Service instead of an IntentService. IntentService is designed to keep running while it has work to do. Once you've finished your onStartCommand method, it tries to stop.

See the docs:

Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

(Emphasis mine)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top