Open In App

How to Build a Simple Alarm Setter App in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to build a much interesting app named Alarm Setter. Alarm plays a vital role in our day-to-day life. Nowadays alarm has become our wake-up assistant. Every mobile phone is associated with an alarm app. We will create this app using android studio. Android Studio provides a great unified environment to build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto because it provides a very large number of app building features and it is also very easy to use. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. In this file, we have added two items ‘TimePicker’ and ‘ToggleButton’. TimePicker is used to capture the alarm time and ToggleButton is added to set the alarm on or off. Initially, ToggleButton is set to off. It is set on when an alarm is set. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <!--Added Time picker just to pick the alarm time-->
    <!--gravity is aligned to center-->
    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
 
    <!--Added Toggle Button to set the alarm on or off-->
    <!--ByDefault toggleButton is set to false-->
    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        android:checked="false"
        android:onClick="OnToggleClicked" />
 
    <!--"OnToggleClicked" method will be implemented in MainActivity.java -->
     
</LinearLayout>


Step 3: Working with the MainActivity.java file

Go to MainActivity.java Class. In MainActivity.java class onToggleClicked( ) method is implemented in which the current hour and the minute is set using the calendar. Alarm services are implemented using AlarmManager class. The alarm is set in such a way that it rings and vibrates repeatedly until the toggle button is turned off. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
 
import androidx.appcompat.app.AppCompatActivity;
 
import java.util.Calendar;
 
public class MainActivity extends AppCompatActivity {
    TimePicker alarmTimePicker;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        alarmTimePicker = (TimePicker) findViewById(R.id.timePicker);
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
 
    }
 
    // OnToggleClicked() method is implemented the time functionality
    public void OnToggleClicked(View view) {
        long time;
        if (((ToggleButton) view).isChecked()) {
            Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
            Calendar calendar = Calendar.getInstance();
 
            // calendar is called to get current time in hour and minute
            calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
            calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
 
            // using intent i have class AlarmReceiver class which inherits
            // BroadcastReceiver
            Intent intent = new Intent(this, AlarmReceiver.class);
 
            // we call broadcast using pendingIntent
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
 
            time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000));
            if (System.currentTimeMillis() > time) {
                // setting time as AM and PM
                if (Calendar.AM_PM == 0)
                    time = time + (1000 * 60 * 60 * 12);
                else
                    time = time + (1000 * 60 * 60 * 24);
            }
            // Alarm rings continuously until toggle button is turned off
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
            // alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (time * 1000), pendingIntent);
        } else {
            alarmManager.cancel(pendingIntent);
            Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
        }
    }
}


Step 4: Working with BroadCastReceiver (AlarmReceiver) class

Create a new java class named “AlarmReceiver.java” at the same place where MainActivity.java class resides. In this class onReceive() method is implemented. Here we have added vibration functionality and a default ringtone that starts to vibrate and ring when the alarm time is scheduled. Below is the code for the AlarmReceiver.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.widget.Toast;
 
import androidx.annotation.RequiresApi;
 
public class AlarmReceiver extends BroadcastReceiver {
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    // implement onReceive() method
    public void onReceive(Context context, Intent intent) {
 
        // we will use vibrator first
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(4000);
 
        Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alarmUri == null) {
            alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }
         
        // setting default ringtone
        Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
 
        // play ringtone
        ringtone.play();
    }
}


Step 5: Playing with colors

Go to the “values” folder first then choose the colors.xml file. In the colors.xml file, you can keep colors of your choice as many as you want to use in your app. You have to just give the name and put the color code of the respective colors. I have kept the AppBar color as “#0F9D58” which we have named as “colorPrimary”. 

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#0F9D58</color>
    <color name="colorPrimaryDark">#0F4C2E</color>
    <color name="colorAccent">#9D0F9B</color>
</resources>


Step 6: Changing theme of the app

Go to the “values” folder first then choose the themes.xml file. In the theme.xml file, we have used “Theme.AppCompat.Light.DarkActionBar” which is a light theme with a dark ActionBar. We can use a light theme with a light action bar using “Theme.AppCompat.Light.LightActionBar”, it all depends on our choice and need. 

XML




<resources>
   
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
 
</resources>


Step 7: Adding permission in “AndroidManifest.xml”

Go to the “AndroidManifest.xml” file. A BroadcastReceiver is registered in AndroidManifest.xml by adding a receiver section after the application section is over. Also, give permission to vibrate using:

<uses-permission android:name=”android.permission.VIBRATE” />

Output:

Here we have manually set the alarm time. You can also set it by adjusting the clock showing in front. You will have to wait for the alarm time. It will continuously show “Alarm! Wake up! Wake up!” and rings and vibrates until the toggle-button is turned off. You can get Source code on the given GitHub link below: https://github.com/Babitababy/Alarm_setter



Last Updated : 17 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads