Android: Таймер обратного отсчета

Я пытаюсь отправить сообщение (SMS, как видно из кода) по прошествии определенного времени. Но я не думаю, что CountDownTimer работает должным образом, потому что он отправляет первое сообщение, как только отображается уведомление.

Вот код ниже

@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);

    mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(),MainActivity2Activity.class);

    Notification notification = new Notification(R.mipmap.ic_launcher,"This is a test message!", System.currentTimeMillis());
    intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

    mManager.notify(0, notification);

    CountDownTimer waitTimer;
    waitTimer = new CountDownTimer(180000, 60000) {

        public void onTick(long millisUntilFinished) {
            sendmessage();
        }

        public void onFinish() {
            //After 60000 milliseconds (60 sec) finish current
            //if you would like to execute something when time finishes
        }
    }.start();


}

Итак, как я могу заставить таймер ждать правильно? Потому что, как я уже сказал, он отправляет первое сообщение, как только вызывается уведомление.

Примечание. И если пользователь нажимает на уведомление, он открывает действие, которое должно убить CountDownTimer, но я не смог этого добиться. Как это можно сделать? Я ничего не мог найти об этом.


person Ashtaroth    schedule 06.05.2015    source источник


Ответы (3)


Наблюдение за CountDownTimer показывает, что первый раз onTick() вызывается сразу после вызова onStart(), а после этого он вызывается через указанные интервалы, как указано.

Во-вторых, первый параметр, переданный 180000, указывает таймеру вызывать onFinish() через 180000 миллисекунд и вызывать onTick() через 60000 миллисекунд между запуском немедленно. Если вы хотите запретить отправку сообщения в первый раз, вы можете выполнить эту простую проверку следующим образом:

CountDownTimer waitTimer;
waitTimer = new CountDownTimer(180000, 60000) {
        boolean firstTime = true;
        public void onTick(long millisUntilFinished) {
            if (firstTime) {
                firstTime = false;
                return;
            }

            sendmessage();
        }
    }

    public void onFinish() {
        //After 180000 milliseconds finish current
        //if you would like to execute something when time finishes
    }
}.start();

OR

Вы также можете использовать TimerTask для выполнения той же операции:

Timer waitingTimer = new Timer();
waitingTimer.schedule(new TimerTask() {
    @Override
    public void run() {
        sendMessage();
        // Add a base condition here to cancel the task if needed..
    }
}, 60000, 180000);
person Asif Mujteba    schedule 06.05.2015
comment
Итак, что я должен использовать вместо CountDownTimer, чтобы он ждал указанное количество времени? - person Ashtaroth; 06.05.2015

Вы можете реализовать с помощью приведенного ниже кода, указав intervalTime как время ожидания в миллисекундах.

Timer waitingTimer = new Timer();
waitingTimer.schedule(new TimerTask() {
    @Override
    public void run() {
        sendMessage();
        waitingTimer.cancel();
    }
}, intervalTime, 5000);
person rafa    schedule 06.05.2015

Для этого можно использовать Timer и TimerTask. Вы можете установить задержку для запуска, а для повторения вы можете установить время, после которого оно должно выполняться снова.

Пример:

Timer timer = null;

public void scheduleTimer (){
    cancelTimer(); // Cancel scheduled timer if any.
    timer = new Timer("message_sender");
    timer.schedule(new TimerTask() {

      @Override
      public void run() {
        //This timer will execute timertask with first delay of 2 seconds and repeat it every 3 seconds.
      }
    }, 2000, 3000);
}

//Method for cancelling any scheduled timer
private void cancelTimer(){
    if (timer != null){
        timer.cancel();
        timer.purge();
        timer = null;
    }
}

Если вы хотите выполнить любую задачу уровня пользовательского интерфейса, то внутри run() вам потребуется выполнить код, используя runOnUiThread

person Rajen Raiyarela    schedule 06.05.2015