set Alarm via Context - Android android.app

Android examples for android.app:Alarm Set up

Description

set Alarm via Context

Demo Code

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class Main{


    public static void set(Context ctx, String className, int alarmId,
            int type, long triggerAtTime, boolean setAlarm) {
        try {//from  w  ww  .  j a  va  2 s. c  om
            Intent intent = new Intent(ctx, Class.forName(className));
            intent.putExtra("alarmId", alarmId);
            PendingIntent pendingIntent = null;
            switch (type) {
            case 1:// activity
                pendingIntent = PendingIntent
                        .getActivity(ctx, 0, intent, 0);
                break;
            case 2:// service
                pendingIntent = PendingIntent.getService(ctx, 0, intent, 0);
                break;
            case 3:// reciever
                pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent,
                        0);
                break;
            default:
                break;
            }

            AlarmManager alarmManager = ((AlarmManager) ctx
                    .getSystemService(Context.ALARM_SERVICE));
            if (setAlarm) {
                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        System.currentTimeMillis() + triggerAtTime,
                        pendingIntent);
            } else {
                alarmManager.cancel(pendingIntent);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   

}

Related Tutorials