我的计时器在Android服务中不起作用。该服务能够发送第一条消息,但它不会在每个定时器间隔内发送消息。
public class AutoStartUp extends Service
{
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
startTimer();
}
public void startTimer()
{
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 5000, 10000); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
}
}
我收到了吐司服务。