计时器无法在Android服务中运行

时间:2016-02-03 16:20:58

标签: android timer

我的计时器在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();
                    }
                });
            }
        };
    }
}

我收到了吐司服务。

0 个答案:

没有答案