Android--simple countdown

1 Design task

1.1 Research Background

Android countdown is a very common function, it can be used in many applications, such as countdown alarm clock, timer, countdown game and so on. Its research background can be traced back to the concepts of timing and countdown, which are an integral part of human social life. In the digital age, we need more accurate, convenient, fast and easy-to-use timing and countdown tools, so the research and development of Android countdown function has great practical significance.

1.2 Research purpose

The purpose of Android countdown is to implement an efficient, accurate, easy-to-use and scalable countdown function, so that users can easily set, start, pause and reset the countdown, and can customize the style and function of the countdown according to their own needs. At the same time, the Android countdown can also provide a convenient interface for developers, so that they can quickly integrate the countdown function into their own applications.

1.3 Research Significance

This course is designed to design a simple countdown application based on the Android platform. The application needs to be connected to the SQLite database and the broadcast receiver to support the user to perform the countdown operation, realize the countdown function and save the countdown time information to the database, and notify the user in the form of broadcast when the countdown ends.

1.4 Research content

The main research content of the countdown is in the countdown function module and the broadcast receiver function module, use the updateCountdownText method to update the countdown time on the UI interface, and use the countdowntimer method to realize the countdown function. Use the SQLiteHelper method, and implement the creation and version update of the database in it.

2 System related technologies

2.1 Broadcast Receiver

In Android, a broadcast receiver (BroadcastReceiver) is a component used to receive broadcast messages sent by the system or applications. Broadcast receivers can be used to implement system-level event processing, such as starting applications, receiving text messages, and receiving phone calls. wait.

Broadcast receivers need to be registered to receive broadcast messages. The registration can be registered dynamically through the <receiver> element in the AndroidManifest.xml file or the code, and this system uses the code dynamic registration method. When a broadcast receiver receives a broadcast message, the system will automatically call its onReceive() method, through which the broadcast message can be processed.

The broadcast receiver can receive the built-in broadcast messages of the system, such as sending a "countdown ended" prompt message after the countdown is over. At the same time, the application can also realize event notification and processing within the application by sending a custom broadcast message.

2.2 SQLite database

SQLite is a lightweight database, a relational database management system that complies with ACID , and it is contained in a relatively small C library. It is a public domain project established by D. Richard Hipp . Its design target is embedded, and it has been used in many embedded products . It occupies very low resources. In embedded devices , only a few hundred K of memory may be enough. It can support mainstream operating systems such as Windows, Linux, Unix, etc., and can be combined with many programming languages .

SQLite is an embedded library and implements a zero-configuration, serverless and transactional SQL database engine. It is used in a wide range of fields, and its single-thread read and write performance is comparable to MySQL, and it guarantees ACID. The storage backend of SQLite is implemented by Btree, and multiple connections can operate concurrently, but only one write is allowed to exist at the same time. SQLite has one database and one file on the hard disk, and the header of each database file contains the meta information of the database, including version, size, Btree root node location, and so on. SQLite manages and reads and writes a database in units of Pages. Each Page defaults to 512 bytes, which can usually be regarded as the size of a hard disk sector.

3 System Analysis

3.1 Feasibility analysis

When implementing an Android countdown feature, you need to ensure that your code handles time units correctly and efficiently and takes into account device resource usage constraints. This is the only way to guarantee reliable and user-friendly functionality of such applications. From the perspective of feasibility, it is completely feasible to realize the Android countdown function, and it is relatively easy to implement. This is due to the rich tools and technical support provided by the Android platform, enabling developers to easily integrate such functions into applications. Overly complex or long-running countdown functions should be avoided, as they may consume device resources, reduce battery life, or affect other device functionality.

3.1.1 Technical Feasibility

During the development process, the Android Studio development tool is used for design, and the UI design directly uses the controls for layout, which is relatively easy to design and has strong visualization. The database design uses the SQLite database, which is a light database and is easy to understand.

3.1.2 Operational Feasibility

The operation of the countdown Android application is relatively simple, and the user can control the application by setting the countdown time, starting the countdown, pausing the countdown and other functions. User experience needs to be considered during the development process to ensure that the operation of the application is smooth and easy to understand.

3.1.3 Economic feasibility

From an economic point of view, the cost of developing a countdown timer Android application is relatively low, mainly including the developer's salary, the purchase of development tools and other costs. However, if the application can be widely used in the market, it will bring certain benefits. Therefore, from an economical feasibility point of view, this design has potential.

3.1.4 Legal feasibility

During the development process, it is necessary to ensure that the application does not infringe the intellectual property rights of others, such as patents, trademarks, etc. In addition, it is also necessary to comply with relevant laws and regulations, such as the Personal Information Protection Act. Therefore, from the perspective of legal feasibility, developing a countdown timer Android application requires strict compliance with relevant laws and regulations.

3.2 Demand Analysis

We understand the pain of some users with poor memory or no fixed goal incentives. They need someone to remind them of what to do next when they are too busy, or remind users of some important events. Give them some pressure and fixed goals, but the existing solutions do not solve these needs well. Our countdown timer is designed to let them remember some important occasions and goals.

4 system design

4.1 Overall system design

The Android countdown system is a countdown application based on the Android platform. Its main function is to help users record countdown events. Its main design includes user interface design, function design and database design. In terms of user interface design, the system needs to provide an intuitive countdown timer UI interface, including numbers, colors, fonts, buttons, etc., to facilitate users to set and operate the countdown timer. In terms of functional design, the system mainly includes the setting of the countdown time and the setting of the broadcast receiver. In terms of database design, the system needs to store the setting information of the countdown timer in the local database, so that the user can restore the previous setting when starting the application next time. Overall, the design of the Android countdown system should focus on user experience, providing easy-to-use functions and an intuitive interface to improve user satisfaction and experience.

4.2 System detailed design

4.2.2 Timer function design

Call CountDownTimer in the MainActivity class to implement the countdown function. Users can set the countdown through the time selector, and use the updateCountdownText() method to update the countdown time on the UI interface [4]. When the countdown ends, the program will insert data into the SQLite database and notify the user that the countdown has ended by broadcasting.

4.3 Database design

Call SQLiteHelper in the MainActivity class, and implement the database creation and version update methods in it. The database connection object is instantiated in MainActivity, and the operation of the database is realized through the object. This module is used to store the countdown event information set by the user. It is also responsible for reading countdown event information from the database for users to view or modify.

5 system realization

5.1 User Interface Implementation

The user interface is implemented using layout files provided by Android, and the logic is controlled by Java code. The information entered by the user is saved to the SQLite database through the interface control. The realization effect is shown in Figure 4.1.

Figure 4.1 Countdown timer

5.2 Realization of countdown function

The countdown function is implemented by inheriting the CountDownTimer class provided by Android. When the user sets the countdown event, the countdown event information is stored in the database, and the background service is started to track the countdown event. The countdown function realization interface is shown in Figure 4.2.

Figure 4.2 Countdown function realization interface

6 System Test

6.1 Test purpose

In order to find and solve the possible defects and problems in the countdown function, so as to verify the correctness, reliability and stability of the function of the application in different situations, so as to ensure that the application can work normally and meet the needs of users. Additionally, testing can uncover potential flaws and vulnerabilities of an application and suggest fixes, thereby improving the quality and reliability of the application. Software testing is the main measure and method to check software problems, which can effectively identify technical deficiencies and problems hidden in software.

6.2 Test method

Black box testing and white box testing are two common approaches in software testing. Black-box testing is the evaluation of software functionality and performance by testing the inputs and outputs of a software system without considering the internal code or structure. Testers only need to judge whether the software conforms to the expected behavior by inputting data and observing the output results. White box testing means that testers need to understand the internal structure, code and algorithm of the software, and evaluate the quality and performance of the software by checking the internal logic of the program. White box testing usually requires testers to have knowledge in programming and software development.

Both black-box testing and white-box testing are usually important components in software testing, and they can complement each other to evaluate the overall quality of software. Black-box testing can help testers evaluate the actual user experience and functionality of a software system, while white-box testing can help testers evaluate the reliability and security of software codes. The system adopts the method of black box testing.

6.3 Test content

When conducting black-box testing of the Android countdown program, the main purpose is to make users stable and convenient to use. Testers need to test the following:

Whether the countdown function works normally; whether the layout and display effect of the user interface meet expectations; whether the performance of the application meets the requirements, including startup time, response time, and resource usage; whether the stability of the application meets the requirements, including long-running and Multitasking switching, etc.; app compatibility on different Android versions and devices.

7 Design summary and experience

7.1 Design Summary

This course designs and develops a simple countdown application based on the Android platform through Android Studio, which can easily realize the countdown function and store key data, and save the countdown in the SQLite database for users to view at any time. The course design also carried out detailed analysis and design on the program's UI interface, model layer, controller layer, etc., and finally realized the expected software functions, successfully completed the test, and achieved the expected results.

7.2 Experience

The design of this course has given me a more comprehensive understanding and understanding of the development of Android Studio. Through the study and practice of the MVC architecture pattern, I can plan and design the development of the application program more standardizedly and clearly, and integrate the software with various Dividing modules and completing corresponding tasks can not only improve the maintainability and scalability of the code, but also enable more effective management and optimization of the development process.

references

[1] Wang Wenxue, Li Fengyin, Wang Wenyu. Design and Implementation of Android-Based Mobile Time Management App [J]. Computer Knowledge and Technology, 2020, 16(02): 63-64+72.

[2] Li Daguo, Chen Wen, Liu Tao. Instrument Recognition Based on Machine Vision on Android Platform [J]. Information Technology, 2020,44(05):108-111+116.

[3] Hu Heng, Xie Caiyun. Android Application Development Optimization [J]. Information and Computer (Theoretical Edition), 2021, 31(20): 84-85.

[4] Li Guocai. Design of Android-based Database Learning System [J]. Computer Programming Skills and Maintenance, 2021(11): 69-70+78.

[5] Gong Chang. Talking about the application of white box testing and black box testing in software testing [J]. Information and Computer. 2021 (1).

[6] Wang Qi. Analysis of computer software testing methods [J]. Science and Technology Innovation, 2021 (04): 93-94.

[7] Wang Weigang, Zhang Rui. Design and Implementation of Parameter Converter Based on Android [J]. Electronic Design Engineering, 2021,35(09):108-113.

The main code is as follows:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">
     <TextView
         android:id="@+id/tv_countdown"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_centerInParent="true"
         android:textSize="50sp"
         android:textColor="@android:color/holo_red_light"
         android:text="00:00:00" />
     <Button
         android:id="@+id/btn_set"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/tv_countdown"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="20dp"
         android:text="设置倒计时" />
</RelativeLayout>

MainActivity.java

package com.example.myapplication;//可自行更改不同的包

import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

public class MainActivity extends AppCompatActivity {

    private TextView tvCountdown;
    private Button btnSet;
    private CountDownTimer countDownTimer;
    private long timeLeftInMillis;
    private SQLiteDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvCountdown = findViewById(R.id.tv_countdown);
        btnSet = findViewById(R.id.btn_set);

        // 创建或打开数据库
        database = SQLiteDatabase.openOrCreateDatabase(getFilesDir().getPath() + "/countdown.db", null);

        // 创建倒计时表
        database.execSQL("CREATE TABLE IF NOT EXISTS countdown (id INTEGER PRIMARY KEY AUTOINCREMENT, time INTEGER)");

        // 设置按钮点击事件
        btnSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog();
            }
        });
        //注册广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK); // 系统每分钟发出的广播
        intentFilter.addAction("com.example.countdown"); // 自定义广播
        registerReceiver(receiver, intentFilter);
    }

    // 显示时间选择器对话框
    private void showTimePickerDialog() {
        TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                startCountdown(hourOfDay, minute);
            }
        }, 0, 0, true);
        timePickerDialog.show();
    }

    // 开始倒计时
    private void startCountdown(int hour, int minute) {
        // 计算剩余时间的毫秒数
        timeLeftInMillis = (hour * 60 + minute) * 60 * 1000;

        // 存储倒计时到数据库中
        ContentValues values = new ContentValues();
        values.put("time", timeLeftInMillis);
        database.insert("countdown", null, values);

        // 开始倒计时
        countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeLeftInMillis = millisUntilFinished;
                updateCountdownText();
            }

            @Override
            public void onFinish() {
                showCountdownFinishedNotification();
                deleteCountdownFromDatabase();
                Intent intent = new Intent("com.example.countdown");
                sendBroadcast(intent);
            }
        }.start();
    }

    // 更新倒计时文本
    private void updateCountdownText() {
        int hours = (int) (timeLeftInMillis / 1000 / 3600);
        int minutes = (int) ((timeLeftInMillis / 1000) % 3600 / 60);
        int seconds = (int) (timeLeftInMillis / 1000 % 60);

        tvCountdown.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
    }

    // 显示倒计时结束通知
    private void showCountdownFinishedNotification() {
        Intent intent = new Intent(MainActivity.this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, "default")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("倒计时结束")
                .setContentText("您设置的倒计时已经结束")
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MainActivity.this);
        notificationManager.notify(1, builder.build());
    }
    // 广播接收器

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {                // 系统每分钟的广播,可以在这里做一些需要每分钟执行的操作
            } else if ("com.example.countdown".equals(intent.getAction())) {                // 自定义广播,倒计时结束时触发
                Toast.makeText(MainActivity.this, "倒计时结束", Toast.LENGTH_SHORT).show();
            }
        }
    };
    // 从数据库中删除倒计时
    private void deleteCountdownFromDatabase() {
        database.delete("countdown", null, null);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 从数据库中取出倒计时
        Cursor cursor = database.rawQuery("SELECT * FROM countdown", null);
        if (cursor.moveToFirst()) {
            timeLeftInMillis = cursor.getLong(cursor.getColumnIndex("time"));
            countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    timeLeftInMillis = millisUntilFinished;
                    updateCountdownText();
                }

                @Override
                public void onFinish() {
                    showCountdownFinishedNotification();
                    deleteCountdownFromDatabase();
                }
            }.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        // 保存当前倒计时到数据库中
        ContentValues values = new ContentValues();
        values.put("time", timeLeftInMillis);
        database.update("countdown", values, null, null);

        // 取消倒计时
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 关闭数据库
        database.close();
    }
}

Guess you like

Origin blog.csdn.net/weixin_65089091/article/details/131069180