【问题标题】:Android service killed immediately after start, despite calling startForeground()Android 服务在启动后立即终止,尽管调用了 startForeground()
【发布时间】:2011-11-07 17:50:02
【问题描述】:

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

【问题讨论】:

    标签: android intentservice


    【解决方案1】:

    您需要考虑使用常规 Service 而不是 IntentServiceIntentService 旨在在有工作要做时继续运行。完成 onStartCommand 方法后,它会尝试停止。

    docs

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

    (强调我的)

    【讨论】:

    • 刚刚修改了我的代码。现在完美运行,感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2016-12-27
    相关资源
    最近更新 更多