fer*_*ral 19 android android-service intentservice android-intentservice
在我的Android应用程序中,我通过调用从Activity中启动IntentService
startService(new Intent(this, MyService.class));
Run Code Online (Sandbox Code Playgroud)
它就像一个魅力.我可以在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
}
}
Run Code Online (Sandbox Code Playgroud)
Sta*_*tan 12
IntentService不是一直运行,但它适用于Intent base.你发送,让我们说一个命令(做一些工作),使用Intent和服务执行该工作并在等待其他Intent之后自行停止.
您应该使用常用的服务而不是IntentService来实现您的目标.应将服务配置为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;
}
Run Code Online (Sandbox Code Playgroud)
要杀死服务本身,您可以使用stopSelf()