即使应用程序关闭,如何保持IntentService运行?

时间:2015-04-08 17:30:26

标签: android android-service intentservice android-intentservice

在我的Android应用程序中,我通过调用

从Activity中启动IntentService
startService(new Intent(this, MyService.class));

它就像一个魅力。我可以在Activies之间移动,按Home键切换到其他应用程序......它仍在工作。但是如果我从最近的屏幕上删除我的应用程序,我的服务就会停止。我怎么能避免这个?换句话说,即使我的应用程序已从最近的应用程序关闭,如何保持我的服务正常运行?

我的服务代码如下:

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
}

}

2 个答案:

答案 0 :(得分:12)

IntentService并非一直在运行,但它适用于Intent base。你发送,让我们说一个命令(做一些工作),使用Intent和服务执行该工作并在等待其他Intent之后自行停止。
您应该使用通常的Service而不是IntentService来实现目标。服务应配置为START_STICKY

答案 1 :(得分:5)

在您的服务类@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()

相关问题