Android



Android Alarm Manager to set a Remainder with Notificationand Sound

Screen Shots:

 Coding:

AlarmActivity.java

package com.example.alarm_manager;
import android.app.Activity;
import android.os.Bundle;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AlarmActivity extends Activity {
    /** Called when the activity is first created. */
    /* Author J M */
    TimePicker TimePicker;
    DatePicker DatePicker;
    Button Setalarm;

    TimePickerDialog timePickerDialog;

    final static int RQS_1 = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
        DatePicker =(DatePicker)findViewById(R.id.datePicker1);
        TimePicker=(TimePicker)findViewById(R.id.timePicker1);
        Calendar now = Calendar.getInstance();

        DatePicker.init(
          now.get(Calendar.YEAR),
          now.get(Calendar.MONTH),
          now.get(Calendar.DAY_OF_MONTH),
          null);
       
        TimePicker.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));
        TimePicker.setCurrentMinute(now.get(Calendar.MINUTE));
       
        Setalarm = (Button) findViewById(R.id.Setalarm);
        Setalarm.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                    Calendar current = Calendar.getInstance();
                   
                    Calendar cal = Calendar.getInstance();
                    cal.set(DatePicker.getYear(),
                            DatePicker.getMonth(),
                            DatePicker.getDayOfMonth(),
                      TimePicker.getCurrentHour(),
                      TimePicker.getCurrentMinute(),
                      00);
                   
                    if(cal.compareTo(current) <= 0){
                     //The set Date/Time already passed
                        Toast.makeText(getApplicationContext(),
                          "Invalid Date/Time",
                          Toast.LENGTH_LONG).show();
                    }else{
                     setAlarm(cal);
                    }
                   
                   }});
           
    }

   
    private void setAlarm(Calendar targetCal) {

        //
        Toast.makeText(AlarmActivity.this, "Alarm is set at " + targetCal.getTime(),
                Toast.LENGTH_LONG).show();
        Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getBaseContext(), RQS_1, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),pendingIntent);

    }

}

 

AlarmReceiver.java

package com.example.alarm_manager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
import android.sax.StartElementListener;
import android.telephony.SmsManager;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
   
     @Override
    public void onReceive(Context context, Intent intent) {
       
         Toast.makeText(context, "Your Time is up!!!!!", Toast.LENGTH_LONG).show();
       Vibrator vib=(Vibrator)context.getSystemService(context.VIBRATOR_SERVICE);    //for Vibration
       vib.vibrate(2000);
      
       Intent i=new Intent(context,song.class);  //song class contain media song
         i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(i);
       }
}

 

song.java

package com.example.alarm_manager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Bundle;

public class song extends Activity{
    MediaPlayer m;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.song);
        m=MediaPlayer.create(getApplicationContext(), R.raw.gaji);
        //create a folder raw inside res folder. and put 1 .mp3 song
        m.start();
      
        AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(song.this);                    
         dlgAlert.setTitle("Remainder !");
         dlgAlert.setMessage("Your time is up !");
         dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int whichButton) {

             m.stop();
             dialog.cancel();
         }
         });
         dlgAlert.show();
     }
}
 

 
Layout:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="20dp"    >

    <TextView
        android:id="@+id/alarmprompt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <DatePicker
        android:id="@+id/datePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    

     <Button
        android:id="@+id/Setalarm"
        android:layout_width="117dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Set Alarm" />

</LinearLayout>


song.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>


AndroidManifest.xml 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarm_manager"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.VIBRATE"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AlarmActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="AlarmReceiver"></receiver>
        <activity android:name="song"></activity>
    </application>

</manifest>

 

35 comments:

  1. This is not working with me it is giving a NULL POINTER EXCEPTION IN RECEIVER SO CAN'T START RECEIVER.
    plz help me out....

    ReplyDelete
    Replies
    1. Hello Raza Abbasi,

      Thank you for your comment. I have sent you the link, to download the full project in Google+. Follow that.

      Thank you

      Delete
  2. This is not working :( Please send me a code!

    ReplyDelete
    Replies
    1. Hi Joao,

      Sent you a link of full code in Google+ . Download it and enjoy

      Delete
  3. Not work, sent me please code. thx

    ReplyDelete
    Replies
    1. Hi Eduard,

      Sent you a link of full code in Google+ . Change the API key in manifest file.

      Delete
  4. I tried it but got stuck. Can you help me!!! I am creating an application in which user wishes to create 4 alarms on same day, so i want to call the subview in which user will be prompted to select time that too 4 times..
    And whenever alarm starts , i want to send notification of it also, to remind user about the event. PLZ HELP....

    ReplyDelete
    Replies
    1. I also want an option for displaying alarm and notification event with either one of these:
      daily, weekly or monthly

      Delete
  5. Hi Puneet,

    For Multiple Alarm you have to store date and time in database. while closing the application u have to check which date is small or closest to d current time and set that date as alarm. see ur Google+. i sent the link. Give me some time to see ur problem

    ReplyDelete
  6. Can you give me the correct link? i'm really appreciate that :)
    thanks before. Great tutorial

    ReplyDelete
    Replies
    1. Hi Be'er,

      Thank you for your comment. As per many requests i'm giving the link to download full project. The link is - http://www.daijioffline.weebly.com

      Delete
  7. Great work!

    Your project solved my "initial idea" problem, now I get what I should do now. Thanks you!

    ReplyDelete
    Replies
    1. Hi Nam Tran,

      welcome. Share the post with your friends. Thanks for your comment.

      Delete
  8. can u send me the full code?

    ReplyDelete
    Replies
    1. Hi Mano,

      Full project link sent u over email. check once.

      Delete
  9. please send me the code its not working.

    ReplyDelete
    Replies
    1. Hi,
      the download link sent to your mail id.

      Delete
  10. Hi can you please send me the codes at kdonovankd@hotmail.com ?? Thanks in advance!

    ReplyDelete
    Replies
    1. Download the code from www.daijioffline.weebly.com

      Delete
  11. Please send me the right code. This really helps thank you so much.

    ReplyDelete
  12. please sen me the right code @@

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Hello Mendonca! I am making an app which allows user to set the alarm time duration and once the duration is set, random messages within "that duration" is displayed with a small audio clip. Also to mention that a message displayed once shouldn't be displayed anymore that day.. every message should be different during the time duration.
    To clarify my point let me give an example.. suppose a user sets the duration to 15 minutes. Now, a message should be displayed after the first 15 mins. Again after the next 15 mins another message, which is completely different, should be displayed with a audio clip. Hope you understood. I have written the code but its not working. It gives a hell lot of errors, and i have been trying since the last 17 days but without success. Every time it fails to execute.... I really need your help..

    ReplyDelete
    Replies
    1. Hey Suprativ, It would be a good App. I sent 1 link on email download that project and edit it. See after every 15 minutes message will come. when a message is displays user clicks. take that time and set next alarm after 15 minutes from that time. and i am sure it will work

      Delete
  15. can u send me full code? thanks in adv

    ReplyDelete
  16. not working plz send one copy in email too

    ReplyDelete
  17. this code is giving error please help me

    ReplyDelete
  18. please send me the code , i need it! :)

    ReplyDelete
  19. please send me the code , i need it! :)

    ReplyDelete
  20. not work, please send me the code

    ReplyDelete
  21. Hello sir, Please send me full code.

    ReplyDelete
  22. Its not working for me. Can you send me the link?

    ReplyDelete

Share It

Followers