Timer в android?

Всем привет, столкнулся с очередной проблемой, хотя казалось что тут может пойти не так..

Дело в том что я не вкурсе как создать стандартный таймер, без создания нового класса, тоесть:
в onCreate создал таймер на выполнение метода в том же классе, тоесть activity

В этом методе будет снова создаваться таймер (нужно отсчитать 8 секунд и убавлять прогрессбар каждую секунду)

Слышал о CountDownTimer (Таймер обратного отсчета), но примеров найти не могу..

Подскажите пожалуйста как релизовать?
  • Вопрос задан
  • 393 просмотра
Решения вопроса 1
@Fibonachy
Нубас
а чем плох класс? Насколько я понял из таймера нужно вызвать таймер? На всякий случай кинул пример "pomodoro" таймера (недавно делал), может быть поможет...
public class MainActivity extends AppCompatActivity {

    WorkClass timer;
    RelaxClass r_timer;
    FloatingActionButton play;
    FloatingActionButton stop;
    TextView display;
    CircularProgressBar circularProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        display = (TextView)findViewById(R.id.time);
        display.setText("02:00");


        circularProgressBar = (CircularProgressBar)findViewById(R.id.progress);

        stop = (FloatingActionButton) findViewById(R.id.stop);
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timer.cancel();
                play.setVisibility(View.VISIBLE);
                stop.setVisibility(View.INVISIBLE);
            }
        });

        play = (FloatingActionButton) findViewById(R.id.play);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stop.setVisibility(View.VISIBLE);
                play.setVisibility(View.INVISIBLE);
                int animationDuration = 60000;
                circularProgressBar.setProgressWithAnimation(100, animationDuration);// Default duration = 1500ms
                timer = new WorkClass(120000, 500);
                timer.start();
            }
        });
    }


    public class WorkClass extends CountDownTimer {

        public WorkClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long seconds = millisUntilFinished / 1000;
            display.setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));
        }

        @Override
        public void onFinish() {
            if (display.getText().equals("00:00")) {
                display.setText("01:00");
                showNotify("Устал?", "Тогда удаляй приложение");
                r_timer = new RelaxClass(60000, 500);
                r_timer.start();
            } else {
                display.setText("2:00");
            }
        }
    }

    public class RelaxClass extends CountDownTimer {

        public RelaxClass(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long seconds = millisUntilFinished / 1000;
            display.setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));
        }

        @Override
        public void onFinish() {
            if (display.getText().equals("00:00")) {
                display.setText("02:00");
                showNotify("Отдохнул?", "Настал час расплаты");
                timer = new WorkClass(120000, 500);
                timer.start();
                r_timer.cancel();
            } else {
                display.setText("2:00");
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void showNotify(String title, String note) {
        // define sound URI, the sound to be played when there's a notification
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // intent triggered, you can add other intent for other actions
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
        Notification mNotification = new Notification.Builder(this)

                .setContentTitle(title)
                .setContentText(note)
                .setSmallIcon(R.drawable.playbutton)
                .setContentIntent(pIntent)
                .setSound(soundUri)
                .build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, mNotification);
    }

}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы