我想創建一個可以每15分鐘檢查一次所需文件的安卓服務。Android服務中的計時器
爲此,我創建了一個示例程序,每10秒鐘使用TTS播放一個文本。並且還使用警報管理器每30秒鐘撥打一次服務
該服務完美呼叫,即使TTS在第一次完美播放,但在50秒後再次呼叫該服務時,計時器並非從0開始相反,從11,12,13開始 - 即使我給了cancel()。
有人能幫我解決這個問題嗎?
以下是在代碼:
public class ServiceLocation extends Service implements OnInitListener
{
TextToSpeech talker;
Timer t;
public int time = 0;
@Override
public void onCreate()
{
super.onCreate();
Log.e("Location1", "Inside onCreate");
}
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
t = new Timer();
Log.e("Location1", "Inside onStart");
talker = new TextToSpeech(this, this);
testMethod();
}
public void testMethod()
{
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
time += 1;
String todis = String.valueOf(time);
if(todis.contains("20"))
{
talker.speak("Testing Service in a App",TextToSpeech.QUEUE_ADD,null);
t.cancel();
t.purge();
}
}
}, 0, 1000);
}
public void onInit(int status)
{
talker.speak("Testing Service in a App",TextToSpeech.QUEUE_ADD,null);
}
}