在我的Android应用程序中,我通过调用从一个Activity中启动一个IntentService
startService(new Intent(this, MyService.class));
它就像一个魅力。 我可以在活动之间移动,按主页button切换到其他应用程序…它仍然在工作。 但是,如果我从最近的屏幕上删除我的应用程序,我的服务停止。 我怎样才能避免这一点? 换句话说,即使我的应用程序是从最近的应用程序closures,我怎么能保持我的服务运行?
我的服务代码如下:
public class MyService extends IntentService { public MyService() { super("MyService"); } @Override protected void onHandleIntent(Intent intent) { //Here I run a loop which takes some time to finish } }
IntentService不是一直在运行,而是在Intent基础上运行。 你发送,让一个命令做(做一些工作),使用意图和服务执行该工作,并等待其他意图后自行停止。
您应该使用通常的服务而不是IntentService来实现您的目标。 服务应configuration为START_STICKY
。
在你的服务类@Override onStartCommand方法中
@Override public int onStartCommand(Intent intent, int flags, int startId) { // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; }
要杀死一个服务本身,你可以使用stopSelf()