Android studio kotlin секундомер

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Stopwatch is a simple Android application developed with Jetpack Compose.

stevdza-san/Stopwatch-Android-App

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Stopwatch — Android App with Jetpack Compose

A simple stopwatch application with jetpack compose using foreground and bound services

This application basically consists of 3 different textunits representing Hours, Minutes and Seconds. Also we got two buttons on the UI. The first button will be changed on the basis of service state and the second button will allow us to cancel the foreground service which will result in resetting of our stopwatch.

You can control the stopwatch either by the UI buttons or with the notification panel. As we are using services, so if we even close the application then also we can track the stopwatch state by notification panel.

Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project. Doing manual dependency injection requires you to construct every class and its dependencies by hand, and to use containers to reuse and manage dependencies.

Читайте также:  Upload php file using php

Hilt provides a standard way to use DI in your application by providing containers for every Android class in your project and managing their lifecycles automatically. Hilt is built on top of the popular DI library Dagger to benefit from the compile-time correctness, runtime performance, scalability, and Android Studio support that Dagger provides.

A bound service is an implementation of the Service class that allows other applications to bind to it and interact with it. To provide binding for a service, you must implement the onBind() callback method. This method returns an IBinder object that defines the programming interface that clients can use to interact with the service.

Foreground services perform operations that are noticeable to the user.

Foreground services show a status bar notification, so that users are actively aware that your app is performing a task in the foreground and is consuming system resources.

Devices that run Android 12 (API level 31) or higher provide a streamlined experience for short-running foreground services. On these devices, the system waits 10 seconds before showing the notification associated with a foreground service. There are a few exceptions; several types of services always display a notification immediately.

About

Stopwatch is a simple Android application developed with Jetpack Compose.

Источник

Chronometer

Компонент Chronometer находился в разделе Date в старых версиях студии. Позволяет пользователю запускать и останавливать начальный отсчёт времени, а также задавать время запуска таймера.

Основные методы:

  • start() — запускает отсчёт времени;
  • stop() — останавливает отсчёт времени;
  • setFormat() — задаёт формат отображения времени. По умолчанию используется формат «MM:SS» или «H:MM:SS». Можно задать свой формат, при этом в строке format первое встреченное «%s», будет заменено на «HH:MM». Например: «Time: %s» будет выводить время «Time: 01:30»

Класс Chronometer имеет интерфейс OnChronometerTickListener.

Поместите на экран активности компонент Chronometer и три кнопки Старт, Стоп, Сброс.

Напишем код для запуска, остановки и сброса секундомера. Весь код сводится обработке щелчков кнопки.

 // Kotlin // Если этот код работает, его написал Александр Климов, // а если нет, то не знаю, кто его писал. package ru.alexanderklimov.as40k import android.os.Bundle import android.os.SystemClock import android.widget.Chronometer import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < private lateinit var chronometer: Chronometer override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) chronometer = findViewById(R.id.chronometer) chronometer.setOnChronometerTickListener < val elapsedMillis: Long = (SystemClock.elapsedRealtime() - chronometer.base) if (elapsedMillis >5000 && elapsedMillis < 6000) < val strElapsedMillis = "Прошло больше 5 секунд" Toast.makeText( this, strElapsedMillis, Toast.LENGTH_SHORT ).show() >> startButton.setOnClickListener < chronometer.base = SystemClock.elapsedRealtime() chronometer.start() >stopButton.setOnClickListener < chronometer.stop() >resetButton.setOnClickListener < chronometer.base = SystemClock.elapsedRealtime() >> > 
// Java package ru.alexanderklimov.chronometer; import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Chronometer; import android.widget.Toast; public class MainActivity extends AppCompatActivity < private Chronometer mChronometer; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mChronometer = findViewById(R.id.chronometer); mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() < @Override public void onChronometerTick(Chronometer chronometer) < long elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase(); if (elapsedMillis >5000) < String strElapsedMillis = "Прошло больше 5 секунд"; Toast.makeText(getApplicationContext(), strElapsedMillis, Toast.LENGTH_SHORT) .show(); >> >); > public void onStartClick(View view) < mChronometer.setBase(SystemClock.elapsedRealtime()); mChronometer.start(); >public void onStopClick(View view) < mChronometer.stop(); >public void onResetClick(View view) < mChronometer.setBase(SystemClock.elapsedRealtime()); >>

Chronometer

В примере также добавлена реализация OnChronometerTickListener — когда секундомер отсчитает 5 секунд, то появится всплывающее сообщение.

Читайте также:  Php изменить значение константы

Обратный отсчёт

В API 24 появился новый метод setCountDown(), позволяющий работать в режиме обратного отсчёта. Родственный XML-атрибут для него — android:countDown. Метод isCountDown() позволит узнать, в каком режиме работает хронометр.

 private Chronometer mChronometer; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mChronometer = findViewById(R.id.chronometer); mChronometer.setCountDown(true); // установим начальное значение mChronometer.setBase(SystemClock.elapsedRealtime() + 1000 * 5); >public void onClick(View view)

Последний отсчёт

Читая документацию, наткнулся на новый метод из API 26 (Android 8.0 Oreo) — isTheFinalCountDown(). Я запустил этот код и чуть не упал со стула от неожиданности — неожиданно в телефоне заиграл видеоролик с песней «The Final Countdown/Последний отсчёт» группы «Европа/Europe». Разработчики развлекаются.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A simple stopwatch app with productivity timer for Android written in Kotlin

License

dan-koller/android-stopwatch

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Android Stopwatch with Productivity Timer

This is a useful stopwatch application inspired by the famous Pomodoro technique! The main idea is to break one long work period into small intervals of work followed by short breaks. In your final application, the user will be able to run a stopwatch and set an upper limit. After the limit is reached, the app will send the user a notification — a reminder to rest.

The app has a stopwatch that can be started, paused, and reset. The user can also set a limit for the stopwatch. When the limit is reached, the app will send the user a notification.

Читайте также:  Make a navbar html

The app is not yet available on the Google Play Store. You need to build the app yourself. You can do this by cloning the repository and building the app with Android Studio.

git clone https://github.com/dan-koller/android-stopwatch.git

Note that the app targets Android 12 (API level 31). The minimum SDK version is 28 (Android 9).

The app is written in Kotlin and uses the Android SDK.

This project is licensed under the MIT License — see the LICENSE file for details.

About

A simple stopwatch app with productivity timer for Android written in Kotlin

Источник

StopWatch Android App Project — Part 1

In this tutorial, we will make a simple Stopwatch Android App step by step and learn some basic stuff about android app development in the tutorial. The tutorial consist of 3 part as shown below:

Part 1: Stopwatch Android App project setup

The final app will look like this:

Stopwatch Android app project

Introduction to Stopwatch App Project:

A stopwatch is a simple app that is used to record or measure time. It has mainly 4 main functions as shown below:

  1. Start: To start the stopwatch time from the beginning or from the pause state.
  2. Stop: To stop the stopwatch time and reset the time to zero.
  3. Pause: To pause the stopwatch time
  4. Lap: To record the laps of the stopwatch time (for example during the race we can use the lap feature to record the duration of different participants in the race)

Creating the project

  1. Open Your Android Studio Click on «Start a new Android Studio project«(Learn how to set up Android Studio and create your first Android project)
  2. Choose «Empty Activity» from the project template window and click Next
  3. Enter the App Name, Package name, save location, language(Java/Kotlin language, we use Java for this tutorial ), and minimum SDK(we are using API 19: Android 4.4 (KitKat) )
  4. Next click on Finish button after filling the above details
  5. Now wait for the project to finish building.

Adding Required files

  1. To make the UI of our app more attractive we will add CardView in our app to do so we have to implement the cardview library in our app, to do so follow the below steps. Go to Gradle Scripts -> build.gradle (Module: app) section and import below dependencies and click the «sync Now» shown at the top:
  #1989C8 #1989C8 #FF0D3D #0B1A37 #ffffff 

With this, we are all set to start writing the actual code of our Stopwatch android App. In the next part we will create the complete UI for our Stopwatch android app and then will start working on the funcationality.

Источник

Оцените статью