Android的定时器设定的延时 [英] Android timer set delay
问题描述
我有一个服务类,我该使用计时器Android应用程序。该定时器被设置为在1分钟(60000毫秒)的延迟运行。我希望用户能够动态地改变这种延迟。通常情况下,在java中我可以只使用timer.setDelay();但是Android不具备此功能。
I have a service class in my Android app which uses a timer. The timer is set to run at a delay of 1min (60000ms). I want the user to be able to dynamically change this delay. Normally, in java I could just use timer.setDelay(); but Android does not have this function.
服务类到目前为止:
public class LocalService extends Service
{
Timer timer = new Timer();
int newDelay;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
mainTask();
}
}, 0, 60000);
}
private void mainTask()
{
//do something
}
private void shutdownService()
{
if (timer != null) timer.cancel();
}
public void onDestroy()
{
super.onDestroy();
shutdownService();
}
private void readNewDelay()
{
InputStream in = openFileInput("updateDelay");
if(in != null)
{
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
newDelay = Integer.parseInt(buffreader.readLine()) * 60000; //value in file is saved in minutes
}
in.close();
}
}
我要的延迟是由活性保存到一个文本文件中。然后,我希望该服务读取该文件,并据此更新其计时器延迟。
The delay I want is saved to a text file by an activity. I then want the service to read this file and update its timer delay accordingly.
推荐答案
您必须销毁计时器对象,并创建一个新的。
You'll have to destroy the timer object and create a new one.
不要忘了,当手机休眠计时器不运行。更好的方法是使用一个警告而不是一个计时器。
Don't forget that timers don't run when the phone sleeps. A better way is to use an Alert instead of a timer.
这篇关于Android的定时器设定的延时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!