English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of the Alarm Clock Setting Method Implemented in Android Programming

This article describes the method of setting an alarm in Android programming. Share it with everyone for reference, as follows:

Alarms are the most common in life, and in Android, they can be implemented through AlarmManager, which is specifically used to set tasks to be completed at a specified time. AlarmManager will execute these events through the onReceive() method, even if the system is in standby mode, it will not affect the operation. You can obtain this service through Context.getSystemService method. There are many methods in AlarmManager, as follows:

Method

Description

Cancel

Cancel AlarmManager service

Set

Set AlarmManager service

setInexactRepeating

Set inexact repeat period

SetRepeating

Set repeat period

setTimeZone

Set time zone


To implement an alarm, you first need to create a class inheriting from BroadcastReceiver, implement the onReceive method to accept this Alarm service, and then call the Alarm component by establishing a connection between Intent and PendingIntent. Set the alarm time using TimerPickerDialog, and after the specified time arrives, the onReceiver method receives the Alarm service and displays the interface.

Firstly, implement the AlarmReceiver class that accepts Alarm service, and use Toast class to prompt the user

public class AlarmReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub
    Toast.makeText(arg0, "The alarm time you set has arrived", Toast.LENGTH_LONG).show();
  }
}

Since BroadcastReceiver service is used, it is necessary to declare it in AndroidManifest.xml:

<receiver>
  android:name=".AlarmReceiver"
  android:process=":remote">
</receiver>

Then you need to set the alarm and cancel alarm time for monitoring:

package cn.edu.pku;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class AlarmActivity extends Activity {
  /** Called when the activity is first created. */
  Button mButton1;
  Button mButton2;
  TextView mTextView;
  Calendar calendar;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    calendar=Calendar.getInstance();
    mTextView=(TextView)findViewById(R.id.TextView01);
    mButton1=(Button)findViewById(R.id.Button01);
    mButton2=(Button)findViewById(R.id.Button02);
    mButton1.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        // TODO Auto-generated method stub
        calendar.setTimeInMillis(System.currentTimeMillis());
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        new TimePickerDialog(AlarmActivity.this, new TimePickerDialog.OnTimeSetListener() {
          public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // TODO Auto-generated method stub
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Intent intent = new Intent(AlarmActivity.this, AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), + (10 * 1000),
                (24 * 60 * 60 * 1000), pendingIntent);
            String tmps = "设置闹钟时间为" + format(hourOfDay) + : +format(minute);
            mTextView.setText(tmps);
          }
        }, hour, minute, true).show();
      }
    });
    mButton2.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(AlarmActivity.this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
        mTextView.setText("Alarm canceled!");
      }
    });
  }
  private String format(int time){
    String str = "" + time;
    if(str.length() == 1{
      str = "0" + str;
    }
    return str;
  }
}

The effect is as follows:

Set Alarm

The current time has reached the time set for the alarm:

Cancel Alarm:

Readers who are interested in more content related to Android can check the special topics on this site: 'Summary of Android Date and Time Operation Skills', 'Android Development Tutorial for Beginners and Advanced', 'Summary of Android Debugging Skills and Common Problem Solving Methods', 'Summary of Android Multimedia Operation Skills (audio, video, recording, etc.)', 'Summary of Android Basic Component Usage', 'Summary of Android View View Skills', 'Summary of Android Layout Layout Skills', and 'Summary of Android Control Usage'.

I hope the description in this article will be helpful to everyone in Android program design.

Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been edited by humans, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like