Output:
1/ Modify your AndroidManifest.xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
<uses-permission android:name= "android.permission.VIBRATE" />
2/Modify your activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TimePicker
android:id="@+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:timePickerMode="clock"/>
<Button
android:id="@+id/set_alarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Alarm"
android:layout_gravity="center_horizontal">
</Button>
<Button
android:id="@+id/EXIT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EXIT"
android:layout_gravity="center_horizontal">
</Button>
</LinearLayout>
package com.tutorialb.alarmmanager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import java.util.Calendar;
import java.util.Random;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TimePicker tp;
private Button setTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tp = findViewById(R.id.time);
setTime = findViewById(R.id.set_alarm);
setTime.setOnClickListener(this);
Button EXIT = (Button)findViewById(R.id.EXIT);
EXIT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
@RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
tp.getHour(),
tp.getMinute(),0);
setExactAlarm(calendar.getTimeInMillis(), 1);
}
@RequiresApi(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
public void setExactAlarm(long triggerAtMillis, int requestCode) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, Alarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, requestCode, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
if (alarmManager != null) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,triggerAtMillis, pendingIntent);
}
else{
alarmManager.cancelAll();
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,triggerAtMillis, pendingIntent);
}
Toast.makeText(this, "Set Alarm", Toast.LENGTH_SHORT).show();
}
}
4/ Create a Alarm Class and Modify
package com.tutorialb.alarmmanager;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class Alarm extends BroadcastReceiver {
public static final String CHANNEL_ID = "alarm_channel";
public static final int NOTIFICATION_ID = 1;
private Ringtone ringtone;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
public void onReceive(Context context, Intent intent) {
playAlarmSound(context);
Toast.makeText(context, "Ringing", Toast.LENGTH_SHORT).show();
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "Alarm Channel", NotificationManager.IMPORTANCE_HIGH);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.baseline_notifications_active_24)
.setContentTitle("Your Alarm")
.setContentText("Wake up Alarm is ringing")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setAutoCancel(true)
.setOngoing(true);
NotificationManagerCompat notificationManagerCompact = NotificationManagerCompat.from(context);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
notificationManagerCompact.notify(NOTIFICATION_ID, builder.build());
}
public void playAlarmSound(Context context) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
ringtone = RingtoneManager.getRingtone(context, alarmUri);
if (ringtone != null) {
ringtone.play();
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
stopAlarmSound();
}
}, 5000);
}
public void stopAlarmSound() {
if (ringtone != null && ringtone.isPlaying()) {
ringtone.stop();
}
}
}