Thursday 29 January 2015

How to Access the Alarm Manager and set up the time for Alarm ?

Getting An Alarm Manager :

AlarmManager am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);

The variable mContext refers to a context object.

For Example: 
If  you are invoking this code from an activity menu, the context variable will be the activity.

Setting Up the Time for the Alarm :

To set the alarm for a particular date and time, you will need an instance in time identified by a Java Calendar object.

public class Utils {

public static Calendar getTimeAfterInSecs(int secs){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, secs) ;
return cal;
}

public static Calendar getCurrentTime(){
Calendar cal = Calendar.getInstance();
return cal;
}

public static Calendar getTodayAt(int hours){
Calendar today = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.clear();

int year = today.get(Calendar.YEAR);
int month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DATE);
cal.set(year,month,day,hours,0,0);
return cal;
}

public static String getDateTimeString(Calendar cal){
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
df.setLenient(false);
String s = df.format(cal.getTime());
return s;
}

}

From this list of Utilities , we will use the function getTimeAfterInSecs(), to look for a time instance that is 30 seconds from now.

Calendar cal = Utils.getTimeAfterInSecs(30);

No comments:

Post a Comment