我正在使用 AlarmManager
运行一个 Service
。 Service
运行正常,我正在手动停止 Service
(单击 Button
),但我需要停止 Service
一段时间后(可能是 10 秒)。我可以使用 this.stopSelf();
,但如何在给定时间后调用 this.stopSelf();
?
最佳答案
这可以很容易地通过使用 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 秒后停止服务。
关于android 服务需要在一段时间后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11503577/