add Alarm - Android Android OS

Android examples for Android OS:Alarm Information

Description

add Alarm

Demo Code

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import java.util.Calendar;

public class Main{
    public static void addAlarm(Context context, int num, String sTime) {

        AlarmManager alarmMgr;/* ww  w. j  av a2  s  .co m*/
        PendingIntent alarmIntent;
        alarmMgr = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);

        // Set the alarm to start at approximately 2:00 p.m.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        setAlarm(calendar, sTime);

        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.putExtra("publish", true);
        alarmIntent = PendingIntent.getBroadcast(context, num, intent, 0);

        // With setInexactRepeating(), you have to use one of the AlarmManager interval
        // constants--in this case, AlarmManager.INTERVAL_DAY.

        alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
                alarmIntent);
    }
    private static void setAlarm(Calendar calendar, String sTime) {

        String speech[] = sTime.split(" ");
        String time = speech[0];
        String timeParts[] = time.split(":");
        int hour = Integer.parseInt(timeParts[0]);
        int minute = Integer.parseInt(timeParts[1]);
        String ampm = speech[1].toUpperCase();
        if (ampm.startsWith("P")) {
            hour += 12;
        }
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
    }
}

Related Tutorials