我正在运行一个Service使用AlarmManager. 运行Service正常,我正在Service手动停止(单击 a 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
Run Code Online (Sandbox Code Playgroud)
现在在您的onCreate()服务中,执行以下操作:
myTimer.schedule(myTask, INTERVAL);
这应该会在 5 秒后停止服务。
| 归档时间: |
|
| 查看次数: |
5064 次 |
| 最近记录: |