我正在开发一个简单的应用程序。在我的应用程序中,我正在使用timerTask,如下所示:
TimerTask saveData=new TimerTask() {
@Override
public void run() {
saveDatatoFile();
}
};
我在我的活动的 onCreate()中调用TimerTask,如:
int file_saving_pollingtime=60000;
timer.schedule(saveData,10000,file_saving_pollingtime);
工作正常。我想实时更改file_saving_pollingtime,因为我使用BroadcastReceiver来读取包含file_saving_pollingtime的特定模式的消息。我成功地从消息中读取了file_saving_pollingtime并将其存储在剪切偏好中。但是根据消息file_saving_pollingtime,我无法刷新定时器的file_saving_pollingtime:
if (frequency.matches(regexStr)){
editor.putString(FILE_FREQUENCY, frequency);
editor.commit();
int fre=Integer.parseInt(sharedPreferences.getString(FILE_FREQUENCY, "0"));
int freq=fre*1000;
Log.d("dfdfdfdf", String.valueOf(freq));
Novipod mv=new Novipod(); //mv is the instance of main activity class
mv.timer.cancel();
mv.timer.schedule(mv.saveData,1000,freq);
}
请帮帮我们
答案 0 :(得分:0)
尝试使用以下代码:
public void rescheduleTimer() { // call it to reschedule the timer
if(timer != null){
timer.cancel();
}
timer = new Timer();
timerTask = new MyTimerTask();
timer.schedule(timerTask,1000,freq);
}
private class MyTimerTask extends TimerTask {
@Override
public void run() {
saveDatatoFile();
}
}