ALARM APP USING TIME PICKER DIALOG

The alarm clock ingredient in smart phones has always been a feature in demand, and at present it won’t be incorrect to say that the maximum crowd utilize their smartphone to wake up instead of a typical alarm clock…!

As it is in vogue, I decided to develop a customized alarm clock application for my android device and would love to share my project with you guys.

The best part of this project is that it uses a TimePickerDialog to directly pick up the required time to trigger alarm and set hours and minutes in the respective TextViews.

We have 2 buttons in the layout, one to set alarm and the other to cancel the alarm. After picking time, tap “set” button to confirm the alarm time.

Remember that at a time, we can set only a single alarm and the cancel button deletes the last saved alarm of our application. As the time triggers, the alarm starts ringing and plays the tone specified in the raw folder of our app.

Let’s start writing the code-snippet. The step-wise procedure is given as follows –

  1. Create a new project in Android Studio:

Specify an appropriate title for the project and select empty activity.

  1. Design xml file of the Activity:

The designing process is a simple drag and drop of various components such as the LinearLayout, TextViews and Buttons.

 

Refer below the code snippet for xml file –

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.igeniusdev.alarmnew.MainActivity"
    android:background="#CAE1FF">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Tap below to Set Alarm"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:textColor="#000000"
        android:textAlignment="center"
        android:textSize="15dp"
        android:layout_marginBottom="15dp" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:id="@+id/ltime"
        android:layout_margin="15dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:id="@+id/textView2"
            android:layout_weight="3"
            android:textColor="#ffffff"
            android:textAlignment="center"
            android:textSize="30dp"
            android:background="@drawable/topwatch"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="20dp"
            android:typeface="serif"
            android:padding="2dp" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:id="@+id/imageView"
            android:layout_weight="1"
            android:src="@drawable/dots" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:id="@+id/textView3"
            android:layout_weight="3"
            android:textColor="#ffffff"
            android:textAlignment="center"
            android:textSize="30dp"
            android:background="@drawable/topwatch"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"
            android:typeface="serif"
            android:padding="2dp" />
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="set"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:background="#4372AA"
        android:textColor="#ffffff"
        android:textSize="16dp"
        android:textStyle="bold" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="cancel"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true"
        android:background="#4372AA"
        android:layout_marginTop="15dp"
        android:textColor="#ffffff"
        android:textSize="16dp"
        android:textStyle="bold" />

</RelativeLayout>

To make the UI look more attractive, I have used various backgrounds for the layout components.

  1. Take permission in Manifest.xml file:

Since an alarm would trigger at any point of time when we are unaware, so a permission to unlock the device would be required.

Specify the following permission –

<uses-permission android:name="android.permission.WAKE_LOCK" />

 

Create a Broadcast Receiver to play the required audio or display a message when alarm goes off:

A broadcast receiver is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.

So, it is mandatory to register the BroadcastReceiver class in order to employ the inbuilt Alarm Service.

To create a BroadcastReciver, Right click left panel in Android Studio –> New –> Other –> Broadcast Receiver –> Render a proper file name e.g. “AlarmReceiver”–> Finish.

The Receiver automatically gets registerd in the Manifest file also. Code in the AlarmReceiver class as follows –

public class AlarmReceiver extends BroadcastReceiver 
{
    public AlarmReceiver( ) {
    }
    @Override
    public void onReceive(Context context, Intent intent)

    {
        Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show( );
        MediaPlayer mediaPlayer = MediaPlayer.create(context,R.raw.abc);
        mediaPlayer.start();
    }
}

 

  1. Save an audio file named abc.mp3 in the raw folder inside res directory:

 

As you can observe in the Receiver class, we have specified a raw component. This is the mp3 file that plays when the alarm goes off. You can place any static mp3 file of your choice.

To create raw folder, directly go to the workspace of the project, create a new folder inside res named “raw” and paste the required mp3 file inside it. This would now get reflected in the Android Studio left panel.

  1. Code in the MainActivity java class as follows:

public class MainActivity extends AppCompatActivity
{
    private Button btnset, btncancel;
    private TextView ehour, emin;
    private LinearLayout ltime;

    Calendar myCalendar = Calendar.getInstance();
    Calendar calSet = (Calendar) myCalendar.clone();

    int hour, minute, hour1, minute1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ehour = (TextView) findViewById(R.id.textView2);
        emin = (TextView) findViewById(R.id.textView3);
        ltime = (LinearLayout) findViewById(R.id.ltime);

        btnset = (Button)findViewById(R.id.button);
        btncancel = (Button)findViewById(R.id.button2);

        ltime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                hour = myCalendar.get(Calendar.HOUR_OF_DAY);
                minute = myCalendar.get(Calendar.MINUTE);
                TimePickerDialog mTimePicker;

                mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @TargetApi(Build.VERSION_CODES.N)
                    @Override
                    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                        //ehour.setText(selectedHour + ":" + selectedMinute);

                        hour1 = selectedHour;
                        minute1 = selectedMinute;

                        ehour.setText(selectedHour +"");
                        emin.setText(selectedMinute +"");

                        calSet.set(Calendar.HOUR_OF_DAY, hour1);
                        calSet.set(Calendar.MINUTE, minute1);

                        if(calSet.compareTo(myCalendar) <= 0){
                            //Today Set time passed, count to tomorrow
                            calSet.add(Calendar.DATE, 1);
                        }
                    }
                }, hour, minute, true);//false bcz not 24 hour time format
                mTimePicker.setTitle("Select Time");
                mTimePicker.show();
            }
        });

        btnset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if (ehour.getText().toString().trim().length() == 0)
                {
                    Toast.makeText(getApplicationContext(), "Plz Set Alarm first", Toast.LENGTH_LONG).show();
                }

                else
                {
                    Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

                    //alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + hour1 + minute1, pendingIntent);
                    alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pendingIntent);
                    //Toast.makeText(this, "Alarm set in " + second + " mili seconds", Toast.LENGTH_LONG).show();
                    Toast.makeText(getApplicationContext(), "Alarm set at " + hour1 + ":" + minute1 + " hours", Toast.LENGTH_LONG).show();
                }
            }
        });

        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if(ehour.getText().toString().trim().length() == 0)
                {
                    Toast.makeText(getApplicationContext(), "There is no saved alarm", Toast.LENGTH_LONG).show();
                }
                else
                {
                    Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                    alarmManager.cancel(pendingIntent);

                    Toast.makeText(getApplicationContext(), "Alarm is cancelled", Toast.LENGTH_LONG).show( );
                    ehour.setText(null);
                    emin.setText(null);
                }
            }
        });
    }
}

The coding part is all done. Now run the project and set alarm to see how wonderfully the project works.

If you enjoy to reading this blog please write your comment to below box also make suggession for better improvement for new upcoming blogs.

Thanks for Reading... (y)

Let's Think together, Say Something !