Android Realizes Simple Alarm Clock Function

  • 2021-11-10 10:40:54
  • OfStack

In this paper, we share the specific code of Android to realize alarm clock through broadcasting for your reference. The specific contents are as follows

1. Create Broadcast Receive RepeatingAlarm. java


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class RepeatingAlarm extends BroadcastReceiver{

 @Override
 public void onReceive(Context context, Intent intent) {
  if (intent.getAction()!=null&&intent.getAction().equals("com.gcc.alarm")) {// Custom action
   intent = new Intent(context,AlarmActivity.class);
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   context.startActivity(intent);
  }
 }
}

2. Broadcast is configured in Manifest. xml:


<receiver 
 android:name=".RepeatingAlarm"
 >
  <intent-filter > 
   <action android:name="com.gcc.alarm"/> 
   </intent-filter> 
</receiver>

3. Set an alarm clock by code


Intent intent = new Intent(this, RepeatingAlarm.class);
intent.setAction("com.gcc.alarm");
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
     am.set(AlarmManager.RTC,
       c.getTimeInMillis(), sender);//c Object for setting the time of the alarm clock Calendar Object 

4. Cancel an alarm clock by code:


/**
 *  Cancel the alarm clock 
 */
private void cancleAlarm(){
 Intent intent = new Intent(AlarmActivity.this,RepeatingAlarm.class);
 intent.setAction("com.gcc.alarm");
 PendingIntent sender = PendingIntent.getBroadcast(AlarmActivity.this, 0, intent, 0);
 // And cancel the alarm.
 AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
  am.cancel(sender);// Cancel the alarm clock 
 }

5. The alarm clock is a pop-up alignment box and plays music. It is realized by AlarmActivity. java class


import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;

public class AlarmActivity extends Activity {

 MediaPlayer mp;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.aty_alarm);
  mp = new MediaPlayer();
  AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
  try {
   mp.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
     file.getLength());
   mp.prepare();
   file.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  mp.setVolume(0.5f, 0.5f);
  mp.setLooping(true);
  mp.start();
  alarmOialog();
 }

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

 @Override
 protected void onDestroy() {
  super.onDestroy();
  if (mp != null) {
   if (mp.isPlaying()) {
    mp.stop();
   }
   mp.release();
  }
 }

 public void alarmOialog() {
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setMessage(" You have unprocessed events ");
  builder.setPositiveButton(" Remind later ",
    new DialogInterface.OnClickListener() {

     @Override
     public void onClick(DialogInterface dialogInterface, int i) {
      alarm();
      finish();
     }
    });

  builder.setNegativeButton(" Stop ", new DialogInterface.OnClickListener() {

   @Override
   public void onClick(DialogInterface dialogInterface, int i) {
    cancleAlarm();
    finish();//  Close a window 
   }
  });
  builder.show().setCanceledOnTouchOutside(false);
  ;

 }

 /**
  *  Cancel the alarm clock 
  */
 private void cancleAlarm() {
  // Create the same intent, and thus a matching IntentSender, for
  // the one that was scheduled.
  Intent intent = new Intent(AlarmActivity.this, RepeatingAlarm.class);
  intent.setAction("com.gcc.alarm");
  PendingIntent sender = PendingIntent.getBroadcast(AlarmActivity.this,
    0, intent, 0);

  // And cancel the alarm.
  AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
  am.cancel(sender);
 }

 private void alarm() {
  //  Get the alarm clock service of the system 
  AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
  //  Time to trigger alarm clock (milliseconds) 
  long triggerTime = System.currentTimeMillis() + 10000;
  Intent intent = new Intent(this, RepeatingAlarm.class);
  intent.setAction("com.gcc.alarm");
  PendingIntent op = PendingIntent.getBroadcast(this, 0, intent, 0);
  //  Start 1 The second time will only be executed 1 A second alarm clock 
  am.set(AlarmManager.RTC, triggerTime, op);
  //  Repeat the alarm clock at a specified time 
  // am.setRepeating(AlarmManager.RTC,triggerTime,2000,op);
 }

}

6. Notes:

1. aty_alarm. xml is an empty layout without adding any components
2. Use MediaPlayer to play audio files in the res/raw directory as follows:


mp = new MediaPlayer();
  AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
  try {
   mp.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
     file.getLength());

7. The function is not perfect, you can modify it if you need it. The alarm clock time setting can get Calendar object through the previous blog post.


Related articles: