Friday, June 7, 2013

Set alarm on specified date/time with DatePicker/TimePicker

Last exercise how to "implement and read DatePicker and TimePicker". This post set alarm on the set date/time.

Set alarm on specified date/time with DatePicker/TimePicker


Create AlarmReceiver.java, its onReceive() method will be called once set time reached.
package com.example.androiddatepicker;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context arg0, Intent arg1) {
  Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();

 }

}


MainActivity.java
package com.example.androiddatepicker;

import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
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 MainActivity extends Activity{
 
 DatePicker pickerDate;
 TimePicker pickerTime;
 Button buttonSetAlarm;
 TextView info;
 
 final static int RQS_1 = 1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  info = (TextView)findViewById(R.id.info);
  pickerDate = (DatePicker)findViewById(R.id.pickerdate);
  pickerTime = (TimePicker)findViewById(R.id.pickertime);
  
  Calendar now = Calendar.getInstance();

  pickerDate.init(
    now.get(Calendar.YEAR), 
    now.get(Calendar.MONTH), 
    now.get(Calendar.DAY_OF_MONTH), 
    null);
  
  pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));
  pickerTime.setCurrentMinute(now.get(Calendar.MINUTE));
  
  buttonSetAlarm = (Button)findViewById(R.id.setalarm);
  buttonSetAlarm.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    Calendar current = Calendar.getInstance();
    
    Calendar cal = Calendar.getInstance();
    cal.set(pickerDate.getYear(), 
      pickerDate.getMonth(), 
      pickerDate.getDayOfMonth(), 
      pickerTime.getCurrentHour(), 
      pickerTime.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){

  info.setText("\n\n***\n"
    + "Alarm is set@ " + targetCal.getTime() + "\n"
    + "***\n");
  
  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);   
 }

}


Layout, /res/layout/activity_main.xml
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold"
        android:layout_gravity="center_horizontal"
        android:autoLink="web" />
    
    <ScrollView 
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            
            <DatePicker 
                android:id="@+id/pickerdate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TimePicker 
                android:id="@+id/pickertime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <Button
                android:id="@+id/setalarm"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Set Alarm"/>
            <TextView 
                android:id="@+id/info"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            
        </LinearLayout>
    </ScrollView>

</LinearLayout>


Modify AndroidManifest.xml to <receiver> of ".AlarmReceiver".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androiddatepicker"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androiddatepicker.MainActivity"
            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" android:process=":remote" />
    </application>

</manifest>


download filesDownload the files.

Next:
- Generate Notification with sound when alarm received

Related:
Generate Alarm, Notification and Ringtone using RingtoneManager


Updated for API Level higher than 19 (KITKAT): Example of using AlarmManager to trigger BroadcastReceiver / alarmManager.set() and setExact().

19 comments:

  1. its not working brah, please fix it, very useful tutorial ;)

    ReplyDelete
  2. I
    t's Working.. Thanks

    ReplyDelete
  3. it is not working when we set particular time and power off and again power On the mobile.now it is not working...

    ReplyDelete
  4. very nice tutorial.....thnk u

    ReplyDelete
  5. its not working.....

    ReplyDelete
  6. Hi,

    Thanks for this tutorial this is working good but it is just showing popup how to set for ringing.

    Thanks,
    Syed

    ReplyDelete
  7. Thanks, This code is working.

    ReplyDelete
  8. It's working, Thank you very much for posting this tutorial,,,,

    ReplyDelete
  9. It's working...
    there isany posibilty such that it should be run if after closing the application also...
    thank you

    ReplyDelete
  10. Its not working...

    ReplyDelete
  11. The only code I found that worked perfectly...

    Thanku...

    ReplyDelete
  12. bhai thnk u so much, ye code perfect kaam kr rha hai, thnk u so much for this beautiful tutorial...!!! BIG THANKS

    ReplyDelete
  13. the code is not working if I'm adding it in an existing project but it is working fine in new standalone notification project. Please tell me how to fix it as it is an important part of my project....

    ReplyDelete
  14. Hello,

    Does the code allows me to set up multiple alarms ? If not, is there a quick way to modify this code so it provides such a thing.
    Do u have a tutorial about storing data file/sharedprefs?

    Greets :)

    ReplyDelete
  15. Hey thank you for the code.But i am facing the same problem as not able to include it in a project.Standalone it is working.any suggestion??

    ReplyDelete
  16. Thank You so much sir! This code helped me a lot. Kindly upload some tutorial about multiple alarms and also about managing alarms in foreground service. Thank you so much!

    ReplyDelete