Android service killed immediately after start, despite calling startForeground()

房东的猫 提交于 2019-12-12 19:13:19

问题


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

回答1:


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)



来源:https://stackoverflow.com/questions/8040460/android-service-killed-immediately-after-start-despite-calling-startforeground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!