2

我的 IntentService 有问题。每次我启动服务时,只要服务空闲,就会调用 onDestroy() 方法。我将我的服务设置为在前台运行,尽管如此,该服务仍然被立即杀死。我的应用程序中只有一个其他活动,它没有调用 stopService()。

阅读开发人员文档给我的印象是调用 startForeground() 将允许您的服务持续存在,即使在空闲时,除非对内存有非常高的需求,还是我读错了?

我的代码如下:

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

1 回答 1

4

您需要考虑使用常规Service而不是IntentService. IntentService旨在在有工作要做时继续运行。一旦你完成了你的onStartCommand方法,它就会尝试停止。

请参阅文档

客户端通过 startService(Intent) 调用发送请求;该服务根据需要启动,使用工作线程依次处理每个 Intent,并在工作结束时自行停止。

(强调我的)

于 2011-11-07T18:10:09.033 回答