我正在运行Serviceusing AlarmManager. 运行正常,Service我正在Service手动停止(单击 a Button),但我需要Service在某个时间后停止(可能是 10 秒)。我可以使用,但是 在给定时间后this.stopSelf();如何调用?this.stopSelf();
4526 次
5 回答
4
这可以很容易地使用timer和timerTask一起完成。
我仍然不知道为什么没有建议这个答案,而是提供的答案没有提供直接和简单的解决方案。
在服务子类中,全局创建它们(您可以不全局创建它们,但您可能会遇到问题)
//TimerTask that will cause the run() runnable to happen.
TimerTask myTask = new TimerTask()
{
public void run()
{
stopSelf();
}
};
//Timer that will make the runnable run.
Timer myTimer = new Timer();
//the amount of time after which you want to stop the service
private final long INTERVAL = 5000; // I choose 5 seconds
现在在您onCreate()的服务中,执行以下操作:
myTimer.schedule(myTask, INTERVAL);
这应该会在 5 秒后停止服务。
于 2013-11-08T14:38:38.730 回答
3
使用服务内的postDelayed方法Handler来完成它。例如:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
stopSelf();
}
}, 10000); //will stop service after 10 seconds
于 2012-07-16T11:58:02.670 回答
3
可能您应该考虑使用IntentService吗?当它没有工作时它会停止,所以你不需要自己管理它的状态。
于 2012-07-16T12:04:52.903 回答
0
- 创建一个
Intent以启动Service. 将 设置action为自定义操作,例如"com.yourapp.action.stopservice"。 - 使用
AlarmManager,启动Intent以启动Service(无论您现在正在做什么)。如果它已经在运行,onStartCommand()这将被传递给。Service - 在
onStartCommand(),检查action传入的Intent。如果action.equals("com.yourapp.action.stopservice"),停止Service使用this.stopSelf()。
于 2012-07-16T12:02:54.263 回答
0
在Kotlin中,您可以使用此代码在onStartCommand()方法中停止服务:
Handler(Looper.getMainLooper()).postDelayed({ stopSelf() }, 10000)
于 2021-01-18T17:11:16.303 回答