Implementation of custom alarm clock developed by Android

Android custom settings alarm clock

Alarm time setting and display

The layout of the alarm clock is very simple, that is, a simple time setting, so you can write a simple layout button yourself, but please repeat it. In addition, use the time dialog TimePickerDialog to set the time, and use Calendar to obtain the time of the current system. AlertDialog.THEME_HOLO_LIGHT sets the dialog style. If it is not set, it is a default circular clock. After setting this, it is a clock style that can scroll up and down. Code display:

	  //Click to set time event
            Calendar c = Calendar.getInstance();
            // Create a TimePickerDialog instance and display it.
            new TimePickerDialog(mContext,  AlertDialog.THEME_HOLO_LIGHT,
                    // Binding listener
                    (tp, hourOfDay, minute) -> {
                        try {
                            if (hourOfDay > 22 || hourOfDay < 5) {
                                Toast.makeText(mContext,"23:00~04:59,Have a good sleep. This is the golden time for a long body~", Toast.LENGTH_LONG).show();
                            } else {
                            //A time to complete the display
                                if(hourOfDay < 10 && minute > 10) {
                                    String times = "0" + hourOfDay + ":" + minute;
                                    tv_play.setText(times);
                                }else if(minute < 10 && hourOfDay < 10) {
                                    String times = "0" + hourOfDay + ":" +  "0"+ minute;
                                    tv_play.setText(times);
                                } else if(minute < 10) {
                                    String times = hourOfDay + ":" +  "0" + minute;
                                    tv_play.setText(times);
                                } else {
                                    String times = hourOfDay + ":" + minute;
                                    tv_play.setText(times);
                                }
                                mDate = tv_play.getText().toString();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //Set initial time
                    , c.get(Calendar.HOUR_OF_DAY)
                    , c.get(Calendar.MINUTE)
                    //true means 24-hour system
                    , true).show();

Default style

Scrollable style

The set clock layout display can be realized by listview or recycleview to see what kind of layout you like on this main page. Here, I use recycleView+gridlayoutManager to display the grid layout, with two cards in a row. It is better to use the adapter to match the recycleview, because it is easy to operate and beautiful.

Alarm clock addition, deletion and modification query

sqlite is a lightweight database built into Android. Addition, deletion, modification and query are all operations on the database. In addition, using sqlite to store the clock data can prevent data loss. Therefore, a plan reminder can be made on the basis of the clock. The contents of the plan can be stored in the database and there is still time. You can bring a self increasing id when creating a data table to facilitate operation. The creation of tables in the database can be searched and written. It is very simple, so I won't repeat it.

/**
 * Dump data, write data to the database and add data
 * @param sqLiteDatabase database
 * @param context content
 * @param repeat repeat
 * @param date time
 * @param count duration
 */
private void insertData(SQLiteDatabase sqLiteDatabase, String context, String repeat,
                       String date, String count){
    try {
        ContentValues values = new ContentValues();
        values.put("context", context);
        values.put("repeat", repeat);
        values.put("time", date);
        values.put("count", count);
        sqLiteDatabase.insert("data",null, values);//New features
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Modify data, write data to the database and add data
 * @param sqLiteDatabase database
 * @param context content
 * @param repeat repeat
 * @param date time
 * @param count duration
 */
private void updateData(SQLiteDatabase sqLiteDatabase, String context, String repeat,
                       String date, String count){
    try {
        ContentValues values = new ContentValues();
        values.put("context", context);
        values.put("repeat", repeat);
        values.put("time", date);
        values.put("count", count);
      sqLiteDatabase.update("data",values,"id=?",new String[]{String.valueOf(mId)});//Modify function
    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * Delete data in database
 * @param sqLiteDatabase database
 * @param id id
 */
private void deleteData(SQLiteDatabase sqLiteDatabase, int id) {
    try {
        sqLiteDatabase.delete("data","id=?",new String[]{String.valueOf(id)});
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Alarm clock on

In the above layout, you can see a key. Click it to turn on the alarm reminder, and turn it off to turn off the alarm reminder. The prompt function for turning on the alarm clock is as follows. Compare the obtained time with the current system time, and AlarmManager sets the reminder. Turning off the alarm clock is a simple AlarmManager cancellation. That kind of reminder is the simple dialog reminder you usually see, so I won't repeat it again.

/**
 * Turn on the alarm clock
 * @param parent Parent class
 * @param hour hour
 * @param minute minute
 * @param position position
 */
private void startAlarm(ViewGroup parent, int hour, int minute, int position) {
    try {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());//Get current time
        //Gets the current millisecond value
        long systemTime = System.currentTimeMillis();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8"));//Set time zone
        c.set(Calendar.HOUR_OF_DAY, hour);//Set a few reminders
        c.set(Calendar.MINUTE, minute);//Set a reminder
        //Get the time set above
        long selectTime = c.getTimeInMillis();
        // If the current time is greater than the set time, it starts from the set time of the next day
        if (systemTime > selectTime) {
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        /* Alarm clock time to a reminder class */
        Intent intent = new Intent(parent.getContext(), ListenerActivity.class);
        @SuppressLint("UnspecifiedImmutableFlag")
        PendingIntent pi = PendingIntent.getActivity(parent.getContext(), 0, intent, 0);
        //Get AlarmManager instance
        AlarmManager am = (AlarmManager)parent.getContext().getSystemService(ALARM_SERVICE);
        //Repeat reminder
        am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 60*60*1000*24, pi);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
   /**
 * Turn off reminder
 * @param parent Parent class
 */
private void stopRemind(ViewGroup parent) {
    try {
        Intent intent = new Intent(parent.getContext(), ListenerActivity.class);
        @SuppressLint("UnspecifiedImmutableFlag")
        PendingIntent pi = PendingIntent.getActivity(parent.getContext(), 0,
                intent, 0);
        AlarmManager am = (AlarmManager)parent.getContext().getSystemService(ALARM_SERVICE);
        //Cancel reminder
        am.cancel(pi);
        Toast.makeText(parent.getContext(), "Reminder turned off", Toast.LENGTH_SHORT).show();
        Intent intents = new Intent("android.intent.action.BOOKCASE_RESTART");
        @SuppressLint("UnspecifiedImmutableFlag")
        PendingIntent pis = PendingIntent.getBroadcast(parent.getContext(), 0,
                intents, 0);
        AlarmManager ams = (AlarmManager)parent.getContext().getSystemService(ALARM_SERVICE);
        //Cancel reminder
        ams.cancel(pis);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

summary

This is a custom alarm clock reminder I recently wrote. The code is not all the code, but the main functions and contents are described above. After a little try, the code is not particularly good, but the functional effect is also realized. Here, record the ideas and code, and make a learning note. I hope you guys can give more advice and bring you some inspiration.

Keywords: Android SQLite

Added by Chris1981 on Fri, 10 Sep 2021 00:36:47 +0300